更新双嵌套嵌入式文档mongo

时间:2015-10-13 01:19:55

标签: mongodb meteor mongodb-query

我收到了一系列问题。每个问题都有一系列答案。每个答案都有一系列以用户ID为单位的投票。

以下是一个示例问题:

{
    "_id" : "PeD7YxzPdbm9MM6rQ",
    "answers" : [ 
        {
            "_id" : "481f791b003ffc58f2adf200",
            "answer" : "d1",
            "votes" : []
        }, 
        {
            "_id" : "cdf02143fa7a10e939df636b",
            "answer" : "d2",
            "votes" : [ 
                "USER1"
            ]
        }, 
        {
            "_id" : "4d552e31fd45a9b2b25e2e3a",
            "answer" : "d3",
            "votes" : [ 
                "USER2"
            ]
        }
    ]
}

我已经更换了ID " RdqMhRkboWzfxNt8a"与USER1 " 4d552e31fd45a9b2b"使用USER2

由于用户只能投票给一个答案,如果他们想要更改答案,我们需要从其他答案中删除他们的投票。

是否可以编写一个mongo查询来删除" USER1"的所有实例。 ?

这是我最好的猜测:

db.getCollection('qa').update(
    { _id: 'PeD7YxzPdbm9MM6rQ'},
    {$pull: {'answers.votes': 'USER1'}}
    );

但是我收到以下错误:

cannot use the part (answers of answers.votes) to traverse the element ({answers: [ { answer: "d1", _id: "481f791b003ffc58f2adf200", author: null, date: new Date(1444697135571) }, { answer: "d2", _id: "cdf02143fa7a10e939df636b", author: null, date: new Date(1444697138399), votes: [ "USER1" ] }, { answer: "sd", _id: "4d552e31fd45a9b2b25e2e3a", author: "RdqMhRkboWzfxNt8a", date: new Date(1444698630266) } ]})

更新:

我可以通过以下逻辑插入新的投票:

QA.update(
    { _id: 'PeD7YxzPdbm9MM6rQ', "answers._id": '481f791b003ffc58f2adf200'},
    {$push: {"answers.$.votes": 'USER1'}}, function(error, result)
    {
        console.log(error, result);
    })

0 个答案:

没有答案