我有以下Collection
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
"myarray" : [
{
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
},
{
userId : ObjectId("613ca5e48dbe673802c2d521"),
point : 2
},
]
}
这些是我的问题
我想进入myarray
如果userId
不存在,它应该附加到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中实现这一点的最佳方式是什么?