Try to search your question here, if you can't find : Ask Any Question Now ?

How do I recursively update a document in mongodb with an embedded subdocument

HomeCategory: stackoverflowHow do I recursively update a document in mongodb with an embedded subdocument
Avatarsourav asked 5 months ago

Wow this is becoming incredibly frustrating to solve and I have spent hours finding a solution on SO and google to no avail. I need to know how (if its possible) in MongoDB to recursively update a document with another document that is a subdocument of the first document so only fields in the document that exists in the subdocument get updated. Ideally using javascript Node mongoose with maybe lodash/underscore to make things fancy.

For simplicity say I have this existing document in mongoDB :

Product
{
    id: 1
    count: 1,
    title: 'sample',
    array:[ 
        {
            a: {
                 A: "nestedField",
                 B: ["123", "456"],
                 C: {
                    id: 'xyz',
                    msgs: [
                        {
                            msg: 'hello'
                        },
                        {
                            msg: 'world'
                        }
                    ]
                 }
            },
            b: {
                oPrice: "9.0"
            },
            price: '10.0',
            img: "9072408.jpg",
            tags: [ "op", "ob", "os" ]
        }
    ]
}

and I have to update this with the following structure

product
{
    id: 1
    count: 1,
    title: 'sample2',
    array:[ 
        {
            a: {
                 A: "nestedField 2",
                 B: ["123", "456"],
                 C: {
                    id: 'xyz',
                    msgs: [
                        {
                            msg: 'hello'
                        },
                        {
                            msg: 'world 2'
                        }
                    ]
                 }
            },
            c: 'some new field',
            price: '10.0'
        }
    ]
}

Note how its same structure as original but only some fields needs updating like title, array[0].a.A, array[0].a.C.msgs
while others don’t eg. count, array[0].a.B, array[0].a.C.id, array[0].price
and there is a new field c in the array value so that needs to be added also.

I tried the following but this replaces the entire document instead of updating any existing fields with its new values and it removes fields which were in the original document that wasn’t in the subdocument like img and tags.

updateOne: {
   filter: { id : product.id },
   update: { $set: product },
   upsert: false
}
1 Answers
Best Answer
AvatarJyoti answered 5 months ago
Your Answer

10 + 11 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com