Search code examples
mongodbmongooseaggregation-frameworkmongodb-update

Update query on in the collection by "_id"


{
    "_id" : "tenant/data/EMAIL/ENGLISH",
    "tenantId" : "tenant2",
    "channelType" : "EMAIL",

    "template" : [ 
        {
            "_id" : "1",
            "templateName" : "abc",
            "effectiveStartDate" : ISODate("2017-01-01T12:00:00.000Z"),
            "modifiedDate" : ISODate("2017-06-02T22:08:55.782Z"),
            "active" : false
        }
    ]
}

I need to update the "templateName" : "xyz" on the basis of "_id" : "tenant/data/EMAIL/ENGLISH"

I have tried these queries but got no success

db.getCollection('data').updateOne({"_id": "tenant/data/EMAIL/ENGLISH"},
                     {$set : { "template.$.templateName" : "XYZ"}}); 

db.getCollection('data').updateOne({"_id": "tenant/data/EMAIL/ENGLISH"},

                     {$set : { "template.templateName" : "XYZ"}}); 

Any help will be appreciated.


Solution

  • I have used positional-all operator to update the array.

    Here is the query:

    db.sample.update(
      {
        "_id": "tenant/data/EMAIL/ENGLISH"
      },
      {
        $set:{
          "template.$[].templateName":"XYZ"
        }
      }
    )
    

    Output

    {
            "_id" : "tenant/data/EMAIL/ENGLISH",
            "tenantId" : "tenant2",
            "channelType" : "EMAIL",
            "template" : [
                    {
                            "_id" : "1",
                            "templateName" : "XYZ",
                            "effectiveStartDate" : ISODate("2017-01-01T12:00:00Z"),
                            "modifiedDate" : ISODate("2017-06-02T22:08:55.782Z"),
                            "active" : false
                    }
            ]
    }
    

    hope this will help :)