Document exist problem

Hi, I need to find a document in my collection with some information about the player and if there isn’t any, insert a new one. I know in C# is FirstOrDefault(), which returns null if nothing is found. Unfortunately, in JAVA, the collection of documents cant be null. Is there some other way to do it?

Code I have so far: mongo - Pastebin.com

Hi @dlabaja,

I guess the best way is to use a method such as FindOneAndUpdate with an upsert:true having only setOnInsert clause only.

This means that the document will try to be fetched and if not existing the upsert part of $setOnInsert will occur.

https://mongodb.github.io/mongo-java-driver/4.2/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#findOneAndUpdate(com.mongodb.client.ClientSession,org.bson.conversions.Bson,java.util.List,com.mongodb.client.model.FindOneAndUpdateOptions)

You can learn more on this article from my colleague:
https://www.mongodb.com/quickstart/java-setup-crud-operations/

Let me know if that helps?

Best regards,
Pavel

Hi, thanks for a fast response
I’m not sure if I understand it, this is my code so far

Bson filter = eq(“uuid”, event.getPlayer().getUniqueId().toString());
Bson updateOperation = push(“uuid”, event.getPlayer().getUniqueId().toString());
UpdateOptions options = new UpdateOptions().upsert(true);
Object updateResult = coll.updateOne(filter, updateOperation, options);

and log: log - Pastebin.com

Hi @dlabaja,

What I suggest is to use findOneAndUpdate() method instead of updateOne:

Bson filter = eq(“uuid”, event.getPlayer().getUniqueId().toString());
 Bson insertDoc =  setOnInsert(“uuid”, event.getPlayer().getUniqueId().toString());
UpdateOptions options = new UpdateOptions().upsert(true);
Document userDocument = coll.findOneAndUpdate(filter, insertDoc, options);

I haven’t tested this code and it is based on the Java article and API

This way if the document exists it will be returned and if not use setOnInsert to set a new document.

Best regards,
Pavel

Hi tried it but still getting MongoTimeout exception. It seems that it cant find the document, so it tries again and again until the exception

Hi @dlabaja,

I actually think that your issue is with the Java version and your client certificate being out of date:

Issues connecting to Atlas Database - #4 by Pavel_Duchovny

See the above way to try and fix it.

Thanks

Ok, it seems I solved it - using JDK 12 wasn’t a good option, so I updated it to 16 instead. Thanks for your support and have a nice day :slight_smile:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.