Can you specify a key for $addToSet in Mongo?

后端 未结 1 1040
半阙折子戏
半阙折子戏 2020-11-22 16:44

I have a document:

{ \'profile_set\' :
  [
    { \'name\' : \'nick\', \'options\' : 0 },
    { \'name\' : \'joe\',  \'options\' : 2 },
    { \'name\' : \'bur         


        
相关标签:
1条回答
  • 2020-11-22 16:55

    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'.

    0 讨论(0)
提交回复
热议问题