Home > database >  How to update nested documents in an array in mongodb document without using positional operator $?
How to update nested documents in an array in mongodb document without using positional operator $?

Time:08-25

I have an issue in which I am not able to use the positional operator to update subdocuments because I am using MongoDB version 3.2 which doesn't support the positional operator $, and I am not able to upgrade MongoDB version to more than 3.2 due to the 32-bit MongoDB support

I want to change the value of the field order in the subdocument to the boolean value false

[
  {
    "_id": 1,
    "products": {
      "books": [
        {
          "id": 1,
          "ordered": true
        },
        {
          "id": 2,
          "ordered": false
        }
      ]
    }
  }
]

and if there is a mongoose way to do it , I would be thankfull

CodePudding user response:

Sadly not much you can do, if you know the index of the array you can use that:

db.collection.update({},
{
  "$set": {
    "products.books.0.ordered": false
  }
})

If you don't you need to find the document first and then update it:

const doc = await db.collection.findOne({});
if (doc) {
    const indexToUpdate = doc.products.items.map((item, index) => ({...item, index})).filter(v => v.item.ordered === true);
    if (indexToUpdate.length) {
        const setBody = {}
        indexToUpdate.forEach((item) => {
            const key = `products.books.${item.index}.ordered`
            setBody[key] = false;
        })
        await db.collection.update({},
            {
                "$set": setBody
            })
    }
}
  • Related