Can you specify a key for $ addToSet in Mongo?

I have a document:

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

and would like to add a new file to the profile_set, if the name does not exist yet (regardless of the option).

So, in this example, if I tried to add:

{'name' : 'matt', 'options' : 0}

he should add it but adding

{'name' : 'nick', 'options' : 2}

should not do anything because the document already exists with the name nick , although option is different.

Mongo seems to fit the whole element, and I end up checking to see if it matches this, and I end up being

 profile_set containing [{'name' : 'nick', 'options' : 0}, {'name' : 'nick', 'options' : 2}] 

Is there a way to do this with $ addToSet or do I need to press another command?

+47
mongodb pymongo
Jan 25 '13 at 18:20
source share
1 answer

You can define your update 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' .

+65
Jan 25 '13 at 18:40
source share



All Articles