0

I have documents in a collection called notificationthat looks as below.

{
"_id" : ObjectId("56438985e68a78f46b1fd9cc"),
"modulename" : "Admin Control Panel",
"modulecode" : "acp",
"eventnames" : [ 
    {
        "name" : "New user account added",
        "code" : 100,
        "_id" : ObjectId("5655fb5d710557d8f7895d94"),
        "emails" : [ 
            "[email protected]"
        ]
    }, 
    {
        "name" : "User permissions changes",
        "code" : 200,
        "_id" : ObjectId("5655fb5d710557d8f7895d93"),
        "emails" : [ 
            "[email protected]", 
            "[email protected]", 
            "[email protected]"
        ]
    }
]
}

I want to replace one object from eventnames array with another object. Lets say want to replace following object

 {
        "name" : "New user account added",
        "code" : 100,
        "_id" : ObjectId("5655fb5d710557d8f7895d94"),
        "emails" : [ 
            "[email protected]"
        ]
    }, 

with following object

    {
        "name" : "New user account added",
        "code" : 100,
        "_id" : ObjectId("5655fb5d710557d8f7895d94"),
        "emails" : [ 
            "[email protected]"
        ],
        "template": {
           "title": "Test Email Title",
           "body": "Test Email Body"
        }
    }

How could I achieve this. Thanks.

1

1 Answer 1

2

You don't need to replace the object here. You can just add the "template" field to the subdocument that matches your criteria using the .update() method with the positional $ operator like this:

db.collection.update(
    { 
        "eventnames": {
            "$elemMatch": {
                "name" : "New user account added",
                "code" : 100,         
                "_id" : ObjectId("5655fb5d710557d8f7895d94") 
            }
        }
    }, 
    { 
        "$set": { 
            "eventnames.$.template": {            
                "title": "Test Email Title",            
                "body": "Test Email Body"         
            }     
        }
    }
)

You can always replace the sub-document that matches your criteria. For example here you can do something like this:

var newObj = {
    "name" : "New user account added",
    "code" : 100,
    "_id" : ObjectId("5655fb5d710557d8f7895d94"),
    "emails" : [ "[email protected]" ],
    "template": { "title": "Test Email Title", "body": "Test Email Body" }
}

{ "$set": { "eventnames.$": newObj } }
Sign up to request clarification or add additional context in comments.

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.