Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findAndModify fails with error: "Cannot update 'field1' and 'field1' at the same time

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

like image 304
Rubycon Avatar asked Jun 02 '14 10:06

Rubycon


1 Answers

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.

like image 157
Neil Lunn Avatar answered Oct 20 '22 03:10

Neil Lunn