我有以下收藏
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
"myarray" : [
{
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
},
{
userId : ObjectId("613ca5e48dbe673802c2d521"),
point : 2
},
]
}
这是我的问题
如果userId
不存在,我想将其推入myarray
,应将其追加到myarray
。如果userId
存在,则应更新为指向的内容。
我找到了这个
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408"),
"myarray.userId" : ObjectId("570ca5e48dbe673802c2d035")
}, {
$set: { "myarray.$.point": 10 }
})
但是如果 userId
不存在,什么也不会发生。
和
db.collection.update({
_id : ObjectId("57315ba4846dd82425ca2408")
}, {
$push: {
"myarray": {
userId: ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}
}
})
但是如果 userId
对象已经存在,则会再次进行推送。
MongoDB中最好的方法是什么?