我有以下收藏
{
"_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中做这件事的最好方法是什么?
发布于 2021-11-09 03:03:12
您可以使用我目前在mongosh中使用的..forEach/..updateOne方法的一个变体来做这样的事情。在.forEach中,您可能能够设置您提到的所有if/条件。
示例..forEach/..updateOne:
let medications = db.medications.aggregate([
{$match: {patient_id: {$exists: true}}}
]).toArray();
medications.forEach(med => {
try {
db.patients.updateOne({patient_id: med.patient_id},
{$push: {medications: med}}
)
} catch {
console.log("Didn't find match for patient_id. Could not add this med to a patient.")
}
})这可能不是最"MongoDB“的方法,但它确实有效,并使您可以自由使用javascript在.forEach中进行操作。
https://stackoverflow.com/questions/37427610
复制相似问题