MongoDB Java 客户端在 "replaceOne" 上将“_id”存储为 null

MongoDB Java Client stores "_id" as null on "replaceOne"

我们已经升级(从 2.11.1)到

            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.4.1</version>

现在当我们这样做时:

        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 的对象)。当我们做

        collection.insertOne(newObject);

然后生成一个正确的“_id”。为什么 "replaceOne" 没有生成正确的 _id?

这是 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.

因此它在创建新文档时使用 _id 作为 null。