mongodb findAndModify update element in array -
there bson document:
{ "_id" : objectid("5718441f5116a60b08000b8c"), "mails" : [ { "id" : 2, "a" : [ { "a" : 1 }, { "a" : 2 } ] }, { "id" : 1, "a" : [ { "a" : 1 }, { "a" : 2 } ] } ] }
i need return , clear array "a" belong "mails.id == x" given document. use findandmodify like:
db.mail.findandmodify({query: {"_id":objectid("5718441f5116a60b08000b8c")}, update: {$set:{"mails.$.a":[]}}, new: false, fields:{"mails":{$elemmatch:{"id":1}}}})
however don't work. problem $set should apply on 1 document in array rather whole document. need projection project out.
if left update blank, return desired part:
{ "_id" : objectid("5718441f5116a60b08000b8c"), "mails" : [ { "id" : 1, "a" : [ { "a" : 1 }, { "a" : 2 } ] } ] }
but don't know how clear array 'a' in 'mails'
you have specify array element match in query:
db.mail.findandmodify({query: {"_id":objectid("5718441f5116a60b08000b8c"), "mails":{$elemmatch:{"id":1}}}, update: {$set:{"mails.$.a":[]}}, new: false, fields:{"mails":{$elemmatch:{"id":1}}}})
mails.$
in update matches first matched element in doc, have match in query. also, query update doc, return old version, since use new: false
, if want updated version set true
.
Comments
Post a Comment