Aneef
Aneef

Reputation: 3729

Updated Nested Collection field value in MongoDB

I have a collection of stores which each element would look like below:

{
 "Name":"Contosco",
 "OperationalDetails" : [ 
        {
            "OperationalDay" : "Sun-Thu",
            "StartTime" : "10:00 AM",
            "EndTime" : "06:00 PM"
        }, 
        {
            "OperationalDay" : "Fri-Sat",
            "StartTime" : "04:00 PM",
            "EndTime" : "09:30 PM"
        }
    ],
}

I need to update the EndTime of all the OperationalDetails of all stores to "06:00 PM"

I'm running the below query

db.stores.update({"Sector.Code": 'GROC'}, { '$set': {"OperationalDetails.$[].EndTime" : '06:00 PM'} },{multi:true} );

But I'm getting the following response

Cannot apply array updates to non-array element OperationalDetails: { 0: { EndTime: "06:00 PM" } }

Any idea how I could achieve this.

Upvotes: 1

Views: 62

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

As you can see from here the syntax you have is working fine.

The error means it's trying to apply an array update to a none array value, this means you have a document that matches your query but the OperationalDetails is not an array but a different type.

To find this object you can use $type, like so:

db.collection.find({
  OperationalDetails: {
    $not: {
      $type: 4
    }
  }
})

Mongo Playground

Upvotes: 1

Related Questions