Updating a double nested embedded document mongo

邮差的信 提交于 2019-12-13 02:26:23

问题


I've got a collection of questions. Each question has an array of answers. Each answer has an array of votes in the form of user id's.

Here is an sample question:

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

I've replaced the IDs "RdqMhRkboWzfxNt8a" with USER1 "4d552e31fd45a9b2b" with USER2

Since a user can only vote for one answer, if they want to change their answer we need to remove their vote from the other answers.

Is it possible to write a mongo query to remove all instances of "USER1" ?

Here is my best guesss:

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

However I get the following error:

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) } ]})

UPDATE:

I am able to insert new votes by the following logic:

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

来源:https://stackoverflow.com/questions/33092648/updating-a-double-nested-embedded-document-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!