我有以下收藏
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
"myarray" : [
{
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
},
{
userId : ObjectId("613ca5e48dbe673802c2d521"),
point : 2
},
]
}
Run Code Online (Sandbox Code Playgroud)
如果userId不存在,我想进入myarray,它应该被附加到myarray.如果userId存在,则应将其更新为point.
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408"), "myarray.userId" : ObjectId("570ca5e48dbe673802c2d035")
},{
$set: {"myarray.$.point": 10}
})
Run Code Online (Sandbox Code Playgroud)
但是如果userId不存在,则没有任何反应.
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408")
},{
$push: {"myarray": {userId: ObjectId("570ca5e48dbe673802c2d035"), point: 10}}
})
Run Code Online (Sandbox Code Playgroud)
但是如果userId对象已经存在,它将再次推送.
在MongoDB中执行此操作的最佳方法是什么?
mongodb ×1