mongodb - Change an existing object in an array but still preserve key uniqueness -



mongodb - Change an existing object in an array but still preserve key uniqueness -

i have document:

class="lang-js prettyprint-override">{ 'profile_set' : [ { 'name' : 'nick', 'options' : 0 }, { 'name' : 'joe', 'options' : 2 }, { 'name' : 'burt', 'options' : 1 } ] }

if want add new object profile_set only if name of object isn't taken, regardless of options, can qualify update query object prevents update if name nowadays in profile_set. in shell:

class="lang-js prettyprint-override">db.coll.update( {_id: id, 'profile_set.name': {$ne: 'nick'}}, {$push: {profile_set: {'name': 'nick', 'options': 2}}})

so perform $push doc matching _id , there isn't profile_set element name 'nick'.

question if later need alter nick's name (and maybe options too...), change existing array object, not add together new one. there way in 1 atomic update operation still honor unique constraint of name?

there 2 conditions, think:

class="lang-js prettyprint-override">var newname = "somename"; var oldname = "nick"; var newoption = 3; // if not alter name db.coll.update({ _id : id, 'profile_set.name' : oldname }, { $set : { "profile_set.$.options" : newoption } }); // if alter 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 } });

mongodb mongodb-query

Comments

Popular posts from this blog

php - Edges appear in image after resizing -

ios8 - iOS custom keyboard - preserve state between appearances -

Delphi change the assembly code of a running process -