MongoDB Java客户端存储"_id"在"replaceOne"上为null [英] MongoDB Java Client stores "_id" as null on "replaceOne"

查看:302
本文介绍了MongoDB Java客户端存储"_id"在"replaceOne"上为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们已经从2.11.1升级到

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);

将插入一个新的文档,该文档的"_id"设置为null(即使以前在该集合中不存在_id为null的对象).

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);

相反,会生成一个正确的"_id".为什么"replaceOne"不能生成正确的_id?

instead then a proper "_id" is generated. Why does "replaceOne" does not generate a proper _id?

推荐答案

replaceOne的预期行为.

MongoDB会将_id字段添加到替换文档(如果替换的话) 过滤器或更换文件中未指定.如果_id为 两者中的值必须相等.

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.

因此,在创建新文档时,它将_id用作null.

So it uses the _id as null when creating a new document.

这篇关于MongoDB Java客户端存储"_id"在"replaceOne"上为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆