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" : [ 
            "email1@abc.com"
        ]
    }, 
    {
        "name" : "User permissions changes",
        "code" : 200,
        "_id" : ObjectId("5655fb5d710557d8f7895d93"),
        "emails" : [ 
            "email1@abc.com", 
            "email2@abc.com", 
            "email3@abc.com"
        ]
    }
]
}

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" : [ 
            "email1@abc.com"
        ]
    }, 

with following object

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

How could I achieve this. Thanks.

styvane
  • 59,869
  • 19
  • 150
  • 156
Jasnan
  • 4,054
  • 2
  • 18
  • 23
  • Possible duplicate of [MongoDB - Update an object in nested Array](http://stackoverflow.com/questions/10522347/mongodb-update-an-object-in-nested-array) – joao Nov 30 '15 at 18:26

1 Answers1

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" : [ "email1@abc.com" ],
    "template": { "title": "Test Email Title", "body": "Test Email Body" }
}

{ "$set": { "eventnames.$": newObj } }
styvane
  • 59,869
  • 19
  • 150
  • 156