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

Mongo DB – Difficulty Updating Multiple within a given document structure

I’ve got an application with a Mongo database that has documents stored with a structure something like this:

{
    "_id" : ...,
    "order_no": 12345,
    "results": [
        {
            "a": "customer",
            "b": "name",
            "result": "John Doe"
        },
        {
            "a": "order_info",
            "b": "date",
            "result": "2022-04-19T00:00:00.000Z"
        },
        {
            "a": "order_type",
            "b": "type",
            "result": "Standard"
        }
    ]
}

So say I need to change the company name to ‘John Doe Ltd’, I’m struggling to update all documents belonging to customer John Doe so that the customer name reflects this change.

I’ve tried

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

collection.updateMany( { "results.a": "customer", "results.b": "name", "results.result": "John Doe" }, [{ $set: { "results.a": "customer", "results.b": "name", "results.result": "John Doe Ltd" } }] )

but I’m getting an error…"Cannot create field 'a' in element..."

I’m hoping that someone can point me in the right direction. Thanks in advance.

>Solution :

db.collection.update({
  "results.a": "customer",
  "results.b": "name",
  "results.result": "John Doe"
},
{
  "$set": {
    "results.$.a": "customer",
    "results.$.b": "name",
    "results.$.result": "John Doe Ltd"
  }
})

For updating specific objects in an array, you would have to use the positional $ operator which will increment the matched document.

But do note that it updates only the first matched object in the array. If more than one object match for a particular query only the first will be updated.

Here is the code for reference:
https://mongoplayground.net/p/o4gFzyQ8HTn

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