Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb upsert in updating an array element

Tags:

mongodb

Want to upsert in object properties in a array of a document

Consider a document in collection m

{ "_id" : ObjectId("524bfc39e6bed5cc5a9f3a33"), 
 "x" : [       
    { "id":0.0, "name":"aaa"},{ "id":1.0, "name":"bbb"}  
 ]
}

Want to add age:100 to { "id":0.0, "name":"aaa"} . Not just age .. But but provision for upsert in the array element {}. So it can contain {age:100,"city":"amd"} (since i am getting this from the application service)

Was trying this... But did not worked as it replaced the entire array element

db.m.update({_id:ObjectId("524bfc39e6bed5cc5a9f3a33"),
     "x" : {
                "$elemMatch" : {
                        "id" : 0.0
                }
}},
{
        $set : {
                "x.$" : {
                    "age": 100
            }
        }
},
{upsert: true}
)

Changed the document to (which i did not wanted)

 { "_id" : ObjectId("524bfc39e6bed5cc5a9f3a33"), 
     "x" : [       
        { "age":100},{ "id":1.0, "name":"bbb"}  
     ]
    }

Is this possible without changing schema.

like image 322
shrw Avatar asked Oct 02 '13 12:10

shrw


1 Answers

$set : {"x.$" : {"age": 100}}

x.$ sets the entire matched array element to {age: 100}

This should work:

db.m.update({_id:ObjectId("524bfc39e6bed5cc5a9f3a33"),
"x.id": 0.0}, {$set: {"x.$.age": 100 }});

Using elemMatch:

db.test.update({x: {$elemMatch: {id: 1}}},{$set:  {"x.$.age": 44}})

Note that the upsert option here, is redundant and wouldn't work if the id isn't present in x because the positional operator $ doesn't support upserting.

like image 176
c.P.u1 Avatar answered Oct 06 '22 14:10

c.P.u1