2

I have many documents (by unique toolname) with the following structure, in db test:

    {
        "_id" : ObjectId("111111111111"),
        "toolname" : "hammer",
        "abilities" : [ 
            {
                "foo" : "blue",
                "bar" : "beagle",
                "LOE" : 0.65
            }, 
            {
                "foo" : "red",
                "bar" : "beagle",
                "LOE" : 0.57
            }, 
            {
                "foo" : "red",
                "bar" : "fish",
                "LOE" : 0.42
            }
        ]
    }

I can find this document with the following query:

db.test.find({"abilities.bar":"beagle","abilities.foo":"red"})

What I would like to do is update the LOE where the two parameters I set in the find query from above match. For example - where "abilities.bar":"beagle" and "abilities.foo":"red", update the "LOE" in that object to .99.

Does Mongo have a built in function where you can set the value of a key only where another key(s) in that object equals some value? Or do I need to create a client side function to return the array index and update based on that? Example:

some function(){...}

db.test.update({"abilities.bar":"beagle","abilities.foo":"red"}
{ $set: { "abilities[x].LOE" : .99 } }
)
isherwood
  • 58,414
  • 16
  • 114
  • 157
mjoyce91
  • 316
  • 2
  • 19

1 Answers1

2

Use $elemMatch as below :

db.collection.update({"abilities":{"$elemMatch":{"bar":"beagle","foo":"red"}}},
                     {"$set":{"abilities.$.LOE":0.99}})
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
Neo-coder
  • 7,715
  • 4
  • 33
  • 52
  • What if I had "sub" abilities and that's where my LOE existed? For example: `{"foo" : "red", "bar" : "beagle", "sub": [{"subability" : "shark", "LOE" : 0.61},{"subability" : "cow", "LOE" : 0.43}]}` and I wanted to update where my initial conditions are met, but I want to update the `LOE` within the object where `subability` is `"shark"`...? – mjoyce91 Jul 07 '15 at 17:16
  • so your document structure looks like `abilities[{"foo" : "red", "bar" : "beagle", "sub": [{"subability" : "shark", "LOE" : 0.61},{"subability" : "cow", "LOE" : 0.43}]}]` right? – Neo-coder Jul 07 '15 at 17:19
  • Yes, if your use of `abilities` refers to the collection name and not some thing inherent to the document. – mjoyce91 Jul 07 '15 at 17:23
  • 1
    two level nested updated having problem [check this](https://jira.mongodb.org/browse/SERVER-831) or you set manually position [like this](http://stackoverflow.com/questions/4121666/updating-nested-arrays-in-mongodb). And still if you want update then used some programming language or script to update . – Neo-coder Jul 07 '15 at 17:29
  • Wow, four years and still no fix. Guess I'll have to create a script. Great to know, thanks again! – mjoyce91 Jul 07 '15 at 17:34