I'm trying to build MongoDB Java findAndModify query.
The main purpose is that I would like to set _id in insert query by myself.
Here is my code:
BasicDBObject findFilter = new BasicDBObject("type", "group")
//
BasicDBObject dialogInsertObject = new BasicDBObject("name", "my group").append("_id", new ObjectId());
//
BasicDBObject dialogUpdateObject = new BasicDBObject("name", "my group");
//
BasicDBObject upsertMap = new BasicDBObject();
upsertMap.append("$setOnInsert", dialogInsertObject);
upsertMap.append("$set", dialogUpdateObject);
DBObject dialogObject = dialogCollection.findAndModify(findFilter,
new BasicDBObject("_id", "1"), null, false, upsertMap, true, true);
And I get an error:
com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" ,
"errmsg" : "exception: Cannot update 'name' and 'name' at the same time" ,
"code" : 16836 , "ok" : 0.0}
Can somebody help please
The essential problem here is this:
db.collection.update(
{ "type": "group" },
{
"$set": { "mygroup": "value" }
"$setOnInsert" { "mygroup": "value" }
}
)
Which is basically what you are trying to do.
You cannot address the same field in a $set
operation as a $setOnInsert
operation.
There is a general problem in the logic that causes the error you are experiencing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With