简体   繁体   中英

Find and update fields inside an array

I am trying to create a better and simpler criteria for an update command. But I can't figure out how I can fetch all users which have any campaigns I search for:

"data" : "a name",    
"campaigns" : [     
          {     "id" : ObjectId("4ff3f07eacf4794426000154"),    "name" : "test" },
          {     "id" : ObjectId("4ff3f07eacf4794426000154"),    "name" : "fisk test2" }
    ]

What I want to do is to update "test" to maybe "OS 2012".

To do this, I thought of using something similar to this:

db.users.update({"campaigns.name": "test"}, {$set : {campaigns: {'test' : 'OS 2012'}}});

The problem with that update statement is that it will probably remove any other campaigns that the user have in it's array? I just want to update "test" to "test2" and the best way I can find right now is to first use $pull and then $addToSet.

Is there a better way? Can you show me an example?

Thanks for you advice and better wisdom.

Learn about the $ positional operator . This code works.

db.users.update({'campaigns.name': 'test'}, 
                {$set: {'campaigns.$.name': 'blah blah'}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM