3

I can't write a query that would update a value of an array that is inside of an object:

Let's say I have a collection that has document entries with the structure like below (There are 2 entries in the example but actually there are a few thousand that I need to update in my db)

/* 1 */
{
    "name" : "Bob",
    "info" : {
        "species" : "human",
        "addresses" : [ 
            "one",
            "two"
        ]
    }
},
/* 2 */
{
    "name" : "John",
    "info" : {
        "species" : "human",
        "addresses" : [ 
            "two",
            "three"
        ]
    },
}

How can I update all documents in this collection so that all addresses in info.addresses array with value one would be changed to have value four?

Examples in mongo db documentation solve such cases when arrays are not inside objects, but I can't make them work with arrays inside objects

Example - this query should update all info.addresses arrays for all documents and change the entry values from one to four

db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$" : "four" } })
2
  • That looks like 2 input objects, what output are you trying to achieve? Have you tried anything? Encountered any specific errors? Commented Feb 19, 2020 at 21:31
  • Sorry for not clarifying, the 2 objects are an example of 2 documents in my collection, I will update the description and add the queries I tried Commented Feb 20, 2020 at 6:10

2 Answers 2

4
db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$[]" : "four" } })

Notice how I added square brackets "[]" in the array specified in $set. It ($[]) is a positional operator in mongodb. You can read more about it in the Mongodb docs.

https://docs.mongodb.com/manual/reference/operator/update/positional-all/

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

1 Comment

Thanks! And if it did the trick, I'd be grateful if you could mark a green tick.
0

replace update to updateMany for update all info.addresses arrays.

db.getCollection('text').updateMany( {'info.addresses':'one'}, {$set:{'info.addresses.$':'two'}} )

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.