Modify an existing object in an array, but keep the key uniqueness

I have a document:

{ 'profile_set' : [ { 'name' : 'nick', 'options' : 0 }, { 'name' : 'joe', 'options' : 2 }, { 'name' : 'burt', 'options' : 1 } ] } 

If I want to add a new object to profile_set only if the name object has not yet been executed, regardless of options , I can assign my update a request object that prevents updating if name already present in profile_set . In the shell:

 db.coll.update( {_id: id, 'profile_set.name': {$ne: 'nick'}}, {$push: {profile_set: {'name': 'nick', 'options': 2}}}) 

Thus, this will only do $push for the document with a suitable _id and where the profile_set element does not exist, where name is 'nick' .

Question But if I then need to change the name Nick (and, possibly, its parameters too ...), then change the existing array object, and not add a new one. Is there a way to do this in one atomic update operation that still respects the unique name constraint?

+3
mongodb mongodb-query
Oct. 27 '14 at 2:48
source share
1 answer

I think there are two conditions:

 var newName = "somename"; var oldName = "nick"; var newOption = 3; // if not change the name db.coll.update({ _id : id, 'profile_set.name' : oldName }, { $set : { "profile_set.$.options" : newOption } }); // if change the name db.coll.update({ _id : id, $and : [ { 'profile_set.name' : { $ne : newName } }, { 'profile_set.name' : oldName } ] }, { $set : { "profile_set.$.name" : newName, "profile_set.$.options" : newOption } }); 
+7
Oct. 27 '14 at 15:08
source share



All Articles