We have upgraded (from 2.11.1) to
org.mongodb
mongo-java-driver
3.4.1
Now when we do this:
UpdateOptions options = (new UpdateOptions()).upsert(true);
BasicDBObject queryObject = new BasicDBObject("_id", newObject.get("_id"));
//where newObject.get("_id") returns "null", i.e. same as
//BasicDBObject queryObject = new BasicDBObject("_id", null);
UpdateResult result = collection.replaceOne(queryObject, newObject, options);
will insert a new document with "_id" set to null (even though no object with _id of null existed previously in the collection). When we do
collection.insertOne(newObject);
instead then a proper "_id" is generated. Why does "replaceOne" does not generate a proper _id?
解决方案
That is expected behavior for replaceOne.
MongoDB will add the _id field to the replacement document if it is
not specified in either the filter or replacement documents. If _id is
present in both, the values must be equal.
So it uses the _id as null when creating a new document.