MongoDB - Update or Insert object in array -


i have following collection

{     "_id" : objectid("57315ba4846dd82425ca2408"),     "myarray" : [               {                 userid : objectid("570ca5e48dbe673802c2d035"),                 point : 5              },              {                 userid : objectid("613ca5e48dbe673802c2d521"),                 point : 2              },              ] } 

this questions

i want push in myarray if userid doesn't exists, should appended myarray. if userid exists, should updated point.

i found this

db.collection.update({   _id : objectid("57315ba4846dd82425ca2408"), "myarray.userid" :  objectid("570ca5e48dbe673802c2d035") },{    $set: {"myarray.$.point": 10} }) 

but if userid doesn't exists, nothing.

and

db.collection.update({   _id : objectid("57315ba4846dd82425ca2408") },{   $push: {"myarray": {userid: objectid("570ca5e48dbe673802c2d035"), point: 10}} }) 

but if userid object exists, push again.

what best way in mongodb.

try this

db.collection.update( { _id : objectid("57315ba4846dd82425ca2408")}, { $pull: {"myarray.userid": objectid("570ca5e48dbe673802c2d035")}} ) db.collection.update( { _id : objectid("57315ba4846dd82425ca2408")}, { $push: {"myarray": { userid:objectid("570ca5e48dbe673802c2d035"), point: 10 }} )


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -