1

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
}

2 Answers 2

1

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" }
])
Sign up to request clarification or add additional context in comments.

Comments

0

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
                }
           ]
        }
    }
)

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.