问题
We have upgraded (from 2.11.1) to
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.1</version>
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?
回答1:
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.
来源:https://stackoverflow.com/questions/42326863/mongodb-java-client-stores-id-as-null-on-replaceone