0

I have document:

{
    "_id" : ObjectId("5152ba0708c164359d5ca616"),
        "info": "Some interesting information.",
    "elements" : [
        {
            "status" : "accepted",
            "id" : "10"
        },
                {
            "status" : "waiting",
            "id" : "20"
        },
                {
            "status" : "accepted",
            "id" : "30"
        }
    ]
}

How can I modify "status" to "accepted" where "status" is "waiting" and "id" is 20?

1
  • You do not want to check status and id at the same time ? Commented Mar 28, 2013 at 12:58

2 Answers 2

3

use positional ("$") operator.

// single
db.collection.update({ _id: ..., "elements.id": "20" }, { $set: { "elements.$.status": "status" } })

// all
db.collection.update({ "elements.id": "20" }, { $set: { "elements.$.status": "status" } }, { multi: true  })
Sign up to request clarification or add additional context in comments.

2 Comments

Where are you checking for the "waiting" status ? If you only check for 20 you may get those elements also where the status is already "accepted"
db.collection.update({ "_id": ..., "elements.id": "20" }, { "$set": { "elements.$.status": "status" } })
1

You have to use elemMatch (http://docs.mongodb.org/manual/reference/projection/elemMatch/) . To match both the items of the array like status and id 20 , then you can use the $set command. The reason behind using elemMatch is that it will make sure that both the criteria is matched on the same subdocument before returning the result

db.CollectionName.update({"_id" : ObjectId("5152ba0708c164359d5ca616") , "elements" : { "$elemMatch : {"status" : "waiting" , "Id" : "20"}}},{ $set : {"elements.$.status" : "accepted"}});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.