Home > Enterprise >  Multi update with mongo in an array of objects
Multi update with mongo in an array of objects

Time:01-21

I am new to mongodb, I have a collection of people with an array of objects inside it, I need to update all the "a.b.c.dates" from less than 2 months ago, with today's date

{
    "_id" : "xxxxxxxxxxxxxxx",
    "a" : {
        "b" : {
            "c" : [ 
                {
                    "date" : ISODate("2021-01-01T09:02:53.217Z"),
                    "value" : "aaa"
                }, 
                {
                    "date" : ISODate("2022-01-01T09:03:38.948Z"),
                    "value" : "bbb"
                }, 
                {
                    "date" : ISODate("2023-01-01T09:15:03.376Z"),
                    "value" : "ccc"
                }
            ]
        }
    },

}
{
    "_id" : "yyyyyyyyyyyyyyy",
    "a" : {
        "b" : {
            "c" : [ 
                {
                    "date" : ISODate("2021-01-01T09:02:53.217Z"),
                    "value" : "aaa"
                }, 
                {
                    "date" : ISODate("2023-01-01T09:03:38.948Z"),
                    "value" : "bbb"
                }, 
                {
                    "date" : ISODate("2023-01-01T09:15:03.376Z"),
                    "value" : "ccc"
                }
            ]
        }
    },

}

I tried this query but it only modifies 1 record per people

db.getCollection('people').update({"a.b.c.date": {$lt: ISODate("2022-11-19")}}, 
{$set: {"a.b.c.$.date": ISODate('2023-01-19T01:07:42.313 00:00')}}, {multi: true})

I expect all the dates to be at 2023

CodePudding user response:

From the update positional $ operator,

the positional $ operator acts as a placeholder for the first element that matches the query document

To update all the items that matched in an array, you should work with positional filtered operator $[<identifier>].

db.getCollection('people').update({
  "a.b.c.date": {
    $lt: ISODate("2022-11-19")
  }
},
{
  $set: {
    "a.b.c.$[c].date": ISODate("2023-01-19T01:07:42.313 00:00")
  }
},
{
  arrayFilters: [
    {
      "c.date": {
        $lt: ISODate("2022-11-19")
      }
    }
  ],
  multi: true
})

Demo @ Mongo Playground

  • Related