问题
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