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.

Abel Tran
  • 19
  • 5
  • Is `places` a collection or is it just a property of a collection? – Rfroes87 Sep 08 '20 at 03:52
  • ```places``` is a Key in a Collection – Abel Tran Sep 08 '20 at 04:14
  • You can use `updateOne` method with `arrayFilters` option to find and update a specific `stores#_id` and update its `open` value. – prasad_ Sep 08 '20 at 04:18
  • ```Thank you!``` – Abel Tran Sep 08 '20 at 04: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?](https://stackoverflow.com/questions/60701824/how-to-add-a-json-in-a-nested-array-of-a-mongodb-document-using-spring) – prasad_ Sep 08 '20 at 05:20
  • Thank [prasad_](https://stackoverflow.com/users/4679320/prasad). I solved my problem with ```arrayFilters``` – Abel Tran Sep 08 '20 at 08:15

1 Answers1

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

Keyur Chavda-kc1994
  • 1,045
  • 1
  • 13
  • 28