Ronald
Ronald

Reputation: 2932

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

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?

Upvotes: 2

Views: 1769

Answers (1)

s7vr
s7vr

Reputation: 75964

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.

Upvotes: 1

Related Questions