Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 key = `products.books.${indexToUpdate[0].index}.ordered`
        await db.collection.update({},
            {
                "$set": {
                    [key]: false
                }
            })
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading