0

I am trying to update a collections document. I need to update IsTripAllocated to true, whose CoverageTimesId is "KhPVAtMrPL0BjVTdJvNOVVSQ" I tried but I am not able to do it.

I try with below code:

reportModel.update({ _id: req.body.ReportId }, 
{ $set: { "RouteDetails.$.CoverageTimes.$.IsTripAllocated" : true } }, 
function (error, success) {
        console.log(success);
});    

Here is my collection:

{
"_id" : ObjectId("5b9f88f6c38c0030d0c487ec"),
"RouteDetails" : [ 
    {
        "CoverageTimes" : [ 
            {
                "RouteId" : "5b9b77d4d5879925a82f1894",
                "RouteName" : "VMS_I-78_EXPRESS_EB_50.6_NY_SIDE_HT_VIA_NJTPK",
                "CoverageTime" : "7:30 - 1:30",
                "CoverageTimesId" : "SJahlTQZWaLfSBK6Hv7zYBQp",
                "IsTripAllocated" : false,
                "IsActive" : true
             }, 
            {
                "RouteId" : "5b9b77d4d5879925a82f1894",
                "RouteName" : "VMS_I-78_EXPRESS_EB_50.6_NY_SIDE_HT_VIA_NJTPK",
                "CoverageTime" : "5:30 - 9:30", 
                "CoverageTimesId" : "VuKoP1WgQGqsmPPnk6IUGauO",
                "IsTripAllocated" : false,
                "IsActive" : true
            }
        ]
    }, 
    {
        "CoverageTimes" : [ 
            {
                "RouteId" : "5b9b7ae9d5879925a82f1896",
                "RouteName" : "I-78 WB MP 67.0 - 50.0 (local lanes)",
                "CoverageTime" : "9:45 - 15:45",
                "CoverageTimesId" : "KhPVAtMrPL0BjVTdJvNOVVSQ",
                "IsTripAllocated" : false,
                "IsActive" : true
            }, 
            {
                "RouteId" : "5b9b7ae9d5879925a82f1896",
                "RouteName" : "I-78 WB MP 67.0 - 50.0 (local lanes)",
                "CoverageTime" : "17:45 - 20:45",
                "DaysOfWeek" : "AllDays",
                "CoverageTimesId" : "rUAm565gb0WTAqNbUjlD6gem",
                "IsTripAllocated" : false,
                "IsActive" : true
            }
        ]
    }
],
"UpdateDate" : null
}

I dont know, what I am doing wrong with my query. Please suggest me how can I achieve it?

David Walschots
  • 12,279
  • 5
  • 36
  • 59
Harish Mahajan
  • 3,254
  • 4
  • 27
  • 49
  • try to use $[] operator if you want to set every IsActive to false – Avij Sep 17 '18 at 12:37
  • Possible duplicate of [MongoDB - Update an object in nested Array](https://stackoverflow.com/questions/34431435/mongodb-update-an-object-in-nested-array) – dnickless Sep 17 '18 at 21:30

1 Answers1

0

You can Update by particular CoverageTimesId

db.getCollection('routes-detail').update(
  { _id:ObjectId("5b9f88f6c38c0030d0c487ec"),
  "RouteDetails.CoverageTimes.CoverageTimesId": "SJahlTQZWaLfSBK6Hv7zYBQp" 
  }, 
  { $set: { "RouteDetails.0.CoverageTimes.$.IsTripAllocated" : true } })
IftekharDani
  • 3,619
  • 1
  • 16
  • 21