1

So I have the following documents in a collection.

{
       _id: "1",
       quantity: 0,
       array: [{name: "test1a", quantity: 10}, {name: "test1a", quantity: 1}, {name: "test1b", quantity: 10}, {name: "test1c", quantity: 1}]
}

{
       _id: "2",
       quantity: 0,
       array: [{name: "test2a", quantity: 10}, {name: "test2b", quantity: 10}, {name: "test2c", quantity: 1}]
}

{
       _id: "3",
       quantity: 0,
       array: [{name: "test3a", quantity: 10}, {name: "test3b", quantity: 10}, {name: "test3c", quantity: 1}]
}

What I wanted was to query all documents in the collection whose it's array contains objects with name = "test1a" and update those object quantity property with a new value.

2
  • update with what? Commented Mar 28, 2018 at 19:38
  • @Krishna with a new int value using $set operator. Commented Mar 28, 2018 at 19:42

2 Answers 2

1

Try something like

db.collection.find({"array.name": "test1a"}).forEach(function(doc){       
var myArray = doc.array;
for (var i in myArray){
    if(myArray[i].name == "test1a"){
        myArray[i].quantity = myArray[i].quantity +1;        
    }
}
 db.collection.update({"_id": doc._id},{$set: {"array":myArray}});
});
Sign up to request clarification or add additional context in comments.

2 Comments

I received the following error: cannot use the part (array of array.quantity) to traverse the element.
The problem is, array.&.quantity only updates the first element inside the array. What I want is to update all array elements that matchs name = "test1a".
0

enter image description here

db.test.updateMany(
    { "array.name": "test1a" }, 
    { "$set": { "array.$[elem].quantity": "newvalue" } },
    { "arrayFilters": [{ "elem.name": "test1a" }] }
)

9 Comments

The problem is, array.&.quantity only updates the first element inside the array. What I want is to update all array elements that matchs name = "test1a".
I got the following error = cannot use the part (array of array.$[elem].quantity) to traverse the element.
did you use arrayfilters option?
Yes, I did use arrayFilters option.
I tested the query and then posted here. Can you post your full query
|

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.