Sufail Kalathil
Sufail Kalathil

Reputation: 647

Update Value in nested array using moogoose

How can I update nested arrays value using express and mongoose, a multi-dimensional array, and need to update a single object keys value? Here is my data model

    {
    "_id":'A'
    "media" : {
            "pictures" : [ 
                {
                    "_id" : 'B',
                    "file_name" : "Uploads\\1625311512442-1_PiHoomzwh9Plr9_GA26JcA.png",
                    "status" : false
                }, 
                {
                    "_id" : 'C',
                    "file_name" : "Uploads\\1625311520688-images.jpg",
                    "status" : false
                }, 
                {
                    "_id" : 'D',
                    "file_name" : "Uploads\\1625311696037-1_PiHoomzwh9Plr9_GA26JcA.png",
                    "status" : false
                }, 
               
            ]
        }
    }

 {
    "_id:"'B'
    "media" : {
            "pictures" : [ 
                {
                    "_id" : 'M',
                    "file_name" : "Uploads\\1625311512442-1_PiHoomzwh9Plr9_GA26JcA.png",
                    "status" : false
                }, 
              
            ]
        }
    }

Here I want to change the status of the file based on the id and image id. A is the id b is the image id

Upvotes: 1

Views: 53

Answers (1)

Arvind Pal
Arvind Pal

Reputation: 521

You can use following query to update the data as your requirement

Users.updateOne(
      {
        _id:"A"
      },
      {
        $set:{
          "media.pictures.$[el].status":true
        }
      },
      {
        arrayFilters:[{
          "el._id":"B"
        }]
      }
    )

I also tried to execute the query in mongoDB, Here is result screenshot

Output

Upvotes: 1

Related Questions