简体   繁体   中英

delete an item inside an array in mongoDB

I have a collection called Subject and inside it a document called "game name" that is structured like this:

{
    "_id": "5234676432",
    "name": "game name",
    "questions": [
        {
            "_id": "12345",
            "question": "question",
            "answer1": "1",
            "answer2": "2",
            "answer3": "3",
            "answer4": "4",
            "correctAns": 2
        },
        {
            "_id": "56789",
            "question": "question2",
            "answer1": "1",
            "answer2": "2",
            "answer3": "3",
            "answer4": "4",
            "correctAns": 3
        }
    ]
}

What I want to do is to delete the question that the user clicks on (let's say he chose the one with the id of "12345" ).

I tried doing that using:

Subject.update({ name: game }, { $pull: { questions: { _id: questionToDelete } } });

But it doesn't seem to work.

I hope this would work for your problem.

Subject.update({name: "game name"}, 
      {$pull: {"questions": {"_id.$oid": "12345"}}}, 
      {multi: true});

Try once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM