1

How would you go about updating the 'status' attribute of the product "car" having a status of 0, to 1, in the purchases array of the following MongoDB Document.

MongoDB Document::

{
    "local": {
        "Name": "Rio",
        "Income": 300000,
        "purchases": [{
                "prod": "car",
                "status": 1
            },
            {
                "prod": "bike",
                "status": 0
            },
            {
                "prod": "car",
                "status": 0
            }
        ]
    }
}

3 Answers 3

2

You need to use $ positional operator with $elemMatch operator

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

db.collection.update(
  { "local.purchases": { "$elemMatch": { "prod": "car", "status": 0 }}},
  { "$set": { "local.purchases.$.status": 1 }}
)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick reply @anthony. Would explain me why we use that $ sign ?
@AnthonyWinzlet Your answer is incorrect. It updates the status for bike not car. You've to use $elemMatch.
1

You need to use $elemMatch to match the array element on both criteria.

db.colname.update(
  {"local.purchases":{"$elemMatch":{"prod":"car", "status":0}}},
  {"$set":{"local.purchases.$.status":1}}
)

Comments

0

The query will be :- db.sample.update({"local.purchases.status": 0}, {$set : {"local.purchases.$.status" : 1} });

Explanation:- Here you will have to use $ operator to reference those purchases which are matched by the find query in the first argument fo the update function. Hope it helps.

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.