MongoDB Java Client stores “_id” as null on “replaceOne”

荒凉一梦 提交于 2019-12-12 01:25:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!