Can you specify a key for $addToSet in Mongo?

You can qualify your update with a query object that prevents the update if the name is 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}}})

So this will only perform the $push for a doc with a matching _id and where there isn’t a profile_set element where name is 'nick'.

Leave a Comment