Sufail Kalathil
Sufail Kalathil

Reputation: 647

update all elements in sub array based on _id

I have this data in Mongo:

{
    "_id" : ObjectId("505fd43fdbed3dd93f0ae088"),
    "categoryName" : "Cat 1",
     "media" : {
        "logo" : "images (1).jpg",
        "pictures" : [ 
            {
                "file_name" : "Plr9_GA26JcA.png",
                "status" : false
            }, 
            {
                "file_name" : "images (1).jpg",
                "status" : false
            }, 
        ]
    }
},
{
    "_id" : ObjectId("505fd43fdbed3dd93f0ae089"),
    "categoryName" : "Cat 2",
     "media" : {
        "logo" : "images (1).jpg",
        "pictures" : [ 
            {
                "file_name" : "Plr9_GA26JcA.png",
                "status" : false
            }, 
            {
                "file_name" : "images (1).jpg",
                "status" : false
            }, 
        ]
    }
}

Now I want to update each picture status to false for id ObjectId("505fd43fdbed3dd93f0ae088")

Like:

{
    "_id" : ObjectId("505fd43fdbed3dd93f0ae088"),
    "categoryName" : "Cat 1",
     "media" : {
        "logo" : "images (1).jpg",
        "pictures" : [ 
            {
                "file_name" : "Plr9_GA26JcA.png",
                "status" : true
            }, 
            {
                "file_name" : "images (1).jpg",
                "status" : true
            }, 
        ]
    }
}

I have already tried with the following

db.services.update(

    // Criteria
    {
        '_id' : ObjectId("505fd43fdbed3dd93f0ae088"),
    },

    // Updates
    {
        $set : {
            'media.pictures.$.status': true
        }
    }
)

Thanks in advance for your help!

Upvotes: 1

Views: 59

Answers (1)

mickl
mickl

Reputation: 49945

You can use the positional all operator for that:

db.collection.update({ _id: ObjectId("505fd43fdbed3dd93f0ae088") }, { $set: { "media.pictures.$[].status": true } })

Mongo Playground

Upvotes: 1

Related Questions