Mongodb upsert from java: how to get the _id of an existing object?

I am using mongo-jackson shell with java and MongoDB. I find the object by querying my field (not the _id field), and then I need to know the value of the _id field, regardless of whether the result was an update or an insert. However, I get an exception:

com.mongodb.MongoException: No objects to return
    at net.vz.mongodb.jackson.WriteResult.getSavedId(WriteResult.java:97)

The exception comes from the wrapper, and not from the MongoDB driver itself.

WriteResult<EntityDocument, String> wr 
   = coll.update(DBQuery.is("corefEntityId", corefEntityId), up, true,  false);

What (if anything) is the right way to do this?

+5
source share
1 answer

You need to use findAndModify and set returnNew to true

You can view the JavaDoc

This code should do the trick, but I have not tested it.

coll.findAndModify(DBQuery.is("corefEntityId", corefEntityId), null, null, false, up, true, false);

0
source

All Articles