如何在一个命令中替换/插入MongoDB中的嵌套数组中的子文档

时间:2018-04-05 19:59:44

标签: mongodb mongodb-query

我的收藏集persons的数组为answers

[{ _id: ObjectId("5abd0550dcc44451cf3272ef"), "name": "Mike", 
"answers": [ { "questionId": 118, "aaa": "xyz", "bbb": "xyz" } ] },
{ _id: ObjectId("5abd0550dcc44451cf3272ab"), "name": "John", 
"answers": [ { "questionId": 101, "aaa": "xyz", "ccc": "xyz" } ] },
{ _id: ObjectId("5abd0550dcc44451cf327212"), "name": "Els", 
"answers": [ { "questionId": 101, "aaa": "qrt", "ccc": "qrt" } ] },
{ _id: ObjectId("5abd0550dcc44451cf32724d"), "name": "Josefien", 
"answers": [ 
    { "questionId": 109, "sss": "xyz", "ttt": "xyz" },
    { "questionId": 110, "nnn": "xyz", "mmm": "xyz" },
    { "questionId": 111, "kkk": "xyz", "lll": "xyz" },
]}]

现在我从一个answer获得了新的person。当questionId已经存在时,我想替换整个子文档answer。如果不是,我想添加一个新的子文档answer

我试过这个,但是没有用,如果它是一个新的子文档就会出错:

db.persons.update(
    { _id: ObjectId("5abd0550dcc44451cf3272ef"), "answers.questionId": answer.questionId },
    { $set: { "answers.$": answer } },
    { upsert: true }
) 

这很好用:

db.persons.update(
    { _id: ObjectId("5abd0550dcc44451cf3272ef") },
    { $pull: { answers: { questionId: answer.questionId } } }
);   

db.persons.update(
    { _id: ObjectId("5abd0550dcc44451cf3272ef") },
    { $addToSet : { answers: answer } }
)

但有没有办法在一个命令中执行此操作?

想象一下,persons集合在现实生活中拥有1000万个文档。每个人都会给出许多新的答案。在这种情况下,高于两个的交易将是非常优选的。

1 个答案:

答案 0 :(得分:-1)

这应该有效:

db.persons.update(
    { _id: ObjectId("5abd0550dcc44451cf3272ef"), "answers.questionId": answer.questionId },
    { $set: { 'answers.$': answer }}
);