5

I would like to create a counter that starts at 1000.

I.e. upsert a mongodb document as follows

  • if the document does not exist, create it with value 1000
  • if the document already exists, increment the value +1

The following does not work:

environment_data:PRIMARY> db.test.findAndModify
   ({query:{key:"mycounter"},
     update:{$inc:{value:1}, $set:{value:1000}},
     upsert:true})

Error: findAndModifyFailed failed: {
 "errmsg" : "exception: Cannot update 'value' and 'value' at the same time",
 "code" : 16836,
 "ok" : 0
}

Is there a way to tell the upsert that for an insert, it needs to $set 1000, but for an update, it needs to $inc 1 ?

Carl D'Halluin
  • 1,052
  • 10
  • 14

1 Answers1

3

You can't do multiple update operations on the same field in one atomic operation, you need to issue out two update queries for this: one to check if the value field exists using the $exists operator then use the $inc operator in the update and another query that checks the non-existence of the value field then set a new value of 1000.

db.test.findAndModify({
    query: { key: "mycounter", value: { $exists: true, $ne : null } },    
    update: { $inc: { value: 1 } },
    upsert: true
});

and

db.test.findAndModify({
    query: { key: "mycounter", value: { $exists: false } },    
    update: { $set: { value: 1000 } },
    upsert: true
});
chridam
  • 100,957
  • 23
  • 236
  • 235