0

Assume we have the following collection, which I have a few questions about:

{
    "_id": ObjectId("5f560d4b5d4b4a0013e6fe34"),
    "places": [
        {
            "_id": "5f55d5c643b7370013605513",
            "stores": [
                {
                    "_id": "5f55d5c643b7370013605514",
                    "open": false
                },
                {
                    "_id": "5f55d5c643b7370013605512",
                    "open": false
                }
            ]
        },
        {
            "_id": "5f3b8d7194beb72ec8975639",
            "stores": [
                {
                    "_id": "5f55eb98ed8c3a2af29fa395",
                    "open": false
                },
                {
                    "_id": "5f55eba2ed8c3a2af29fa39b",
                    "open": false
                }
            ]
        }
    ]
}

I want to find 1 store with _id at stores and update key open of this store to true.

6
  • Is places a collection or is it just a property of a collection? Commented Sep 8, 2020 at 3:52
  • places is a Key in a Collection Commented Sep 8, 2020 at 4:14
  • You can use updateOne method with arrayFilters option to find and update a specific stores#_id and update its open value. Commented Sep 8, 2020 at 4:18
  • Thank you! Commented Sep 8, 2020 at 4:29
  • You can use this post as an example to update a nested array: How to add a json in a nested array of a mongodb document using Spring? Commented Sep 8, 2020 at 5:20

1 Answer 1

1

You can update specific sub-document with arrayFilters options of an update query.

As per your example if you want to update a sub-document places' stores which have _id is 5f55eb98ed8c3a2af29fa395 then you can use the following query to update.

 db.collection.update({match-record},
 {
   "$set":{
      "places.stores.$[elem].open": true
    }
 },
 {
    "arrayFilters": [{
        "elem._id": "5f55eb98ed8c3a2af29fa395"            
    }],
    "multi": true
 });

Note: This will work in mongo 3.6+ versions only.

For more info: https://docs.mongodb.com/master/reference/operator/update/positional-filtered

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

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.