5

I would like to perform multiple update on subdocuments "value" field if the "oid" and "instance" fields match. I can do it one subdocument at a time, but is there a way to do it for multiple

-- This works for one --

db.myTable.update({ "data" : { "$elemMatch" : { "oid" : "1.3.6.1.4.1.111.3.10.2.5.35.3", 
                                                "instance" : "0" } }, 
                    "$atomic" : "true" },
                  { $set: { "data.$.value": "change good" }}, 
                  false, 
                  true);



  "_id" : 483,
  "data" : [{
      "oid" : "1.3.6.1.4.1.111.3.10.2.5.35.3",
      "instance" : "0",
      "value" : "0"
    }, {
      "oid" : "1.3.6.1.4.1.111.3.999.2.5.2",
      "instance" : "0",
      "value" : "aaa"
    }, {
      "oid" : "1.3.6.1.4.1.111.3.30.5.1.1",
      "instance" : "0",
      "value" : "BBB"
    }]}
2

1 Answer 1

8

This question has been asked a few times already, but no, you can't do this in one go. To repeat the answer:

You will have to do this yourself in your application code, by querying the document, and looping over all of your nested documents; and then save it back to MongoDB.

In order to prevent race conditions with this, please have a look at the section compare and swap at http://www.mongodb.org/display/DOCS/Atomic+Operations

There is currently an open ticket for this to add this functionality to MongoDB. You might want to up-vote it: https://jira.mongodb.org/browse/SERVER-1243

Sign up to request clarification or add additional context in comments.

1 Comment

Well old question and answer and the mongodb jira ticket actually is closed of this year! 🎉 However, where I work we run an older version of mongo, so I wrote a proof of concept in node.js on how to do it iteratively github.com/KATT/mongodb-deep-set

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.