Jayesh Singh
Jayesh Singh

Reputation: 726

Updating single object in array in mongoDB

My collection is in below format,

{
"_id" : ObjectId("5d01fddd3f21c407582e578d"),
"device_name" : "Test Alarm Device",
"description" : "test",
"parameters" : [ 
    {
        "parameter_name" : "CO2",
        "status" : "on"
    },
    {
        "parameter_name" : "NO",
        "status" : "on"
    },
    {
        "parameter_name" : "O2",
        "status" : "on"
    }
}

Now I wish to overwrite(update) complete object where "parameter_name" : "O2".

For example, in new collection it will look like...

{
    "parameter_name" : "O2",
    "status" : "on",
    "is_active": true,
    "min": 5
}

Upvotes: 1

Views: 31

Answers (2)

mickl
mickl

Reputation: 49985

Use $out to replace existing collection, $addFields to overwrite existing array and $map with $cond to update elements based on some criteria. To build a new object based on existing one you can use $mergeObjects, try:

db.collection.aggregate([
    {
        $addFields: {
            parameters: {
                $map: {
                    input: "$parameters",
                    in: {
                        $cond: [
                            { "$eq": [ "$$this.parameter_name", "O2" ] },
                            { $mergeObjects: [ "$$this", { "is_active": true, "min": 5 } ] },
                            "$$this"
                        ]
                    }
                }
            }
        }
    },
    { $out: "collection" }
])

Upvotes: 1

Lucas Wieloch
Lucas Wieloch

Reputation: 818

This will do, but I don't think it is the best solution:

db.collection.updateOne({
_id: ObjectId("5d01fddd3f21c407582e578d"),
{ $set: { "parameters" : [ 
                {
                    "parameter_name" : "CO2",
                    "status" : "on"
                },
                {
                    "parameter_name" : "NO",
                    "status" : "on"
                },
                {
                    "parameter_name" : "O2",
                    "status" : "on",
                    "is_active": true,
                    "min": 5
                }
           ]
        }
    }
)

Upvotes: 0

Related Questions