Home > Back-end >  Update deep nested array (not a array of documents/objects) in mongoDB
Update deep nested array (not a array of documents/objects) in mongoDB

Time:10-08

I have a document which looks like:

{
    _id: 'random123',
    days: [
        {
            _id: "1a",
            day: "Monday",
            tasks: ["shopping", "playing", "movie"]
        },
        {
            _id: "1b",
            day: "Tuesday",
            tasks: ["office", "travel", "relax"]
        },
    ]
}

Now I want to update "office" to "enjoy" in document of id "1b" of days array

I've tried achieving it using following code's

  1. await Schema.updateOne({_id: ObjectId("random123")}, {$set: {"days.$[outer].$[inner]": "enjoy"}}, {arrayFilters: [{"outer._id": ObjectId("1b")}, {"inner.food": "office"}]})

This one code even throws an error

  1. await Schema.updateOne({_id: ObjectId("random123")}, {$set: {"days.$[outer].tasks.$[inner]": "enjoy"}}, {arrayFilters: [{"outer._id": ObjectId("1b")}, {"inner.food": "office"}]})

  2. await Schema.updateOne({_id: ObjectId("random123"), days: {$elemMatch: {"_id": ObjectId("1b"), "tasks": "office"}}}, {$set: {"foods.$[outer].$[inner]": "enjoy"}}, {arrayFilters: [{"outer._id": ObjectId("1b")}, {"inner.food": "office"}]})

None of above code works; execpt 2nd, neither of them throws any error

I am unable to find any solution to this neither on stackoverflow nor on mongoDB official documentation

CodePudding user response:

Try to use $[] in your $addToSet for multiple positional element

db.collection.update({
  _id: "random123"
},
{
  $set: {
    "days.$[d].tasks.$[t]": "enjoy"
  }
},
{
  arrayFilters: [
    {
      "d._id": "1b"
    },
    {
      "t": "office"
    }
  ]
})

Mongo playground

Official documentation for identifier $[]

CodePudding user response:

use arrayFilter

db.collection.update({
  "days._id": "1b",
  "days.tasks": "office"
},
{
  "$set": {
    "days.$[item].tasks.$[element]": "enjoy"
  }
},
{
  arrayFilters: [
    {
      "item._id": "1b"
    },
    {
      "element": "office"
    }
  ],
  multi: true
})

mongoplayground

  • Related