Mijanur Rahman
Mijanur Rahman

Reputation: 1182

Remove array elements from another array

I have a MongoDB object like:

{

    "courseName": "ML",
    "user": ObjectId("6087dc4c2ba7a828363c9fca"),
    "questions": [  
        {

            "topics": [
               "a","b"
            ],
        },
        {
            "topics": [
                "a","b","d"
            ],
        }
    ]
}

I want to find the questions with courseName and user into questions, I want to remove the topic(s) that matches with the input topic.

How can I do this?

If my input is ["a"] then the update output should look like:

{

    "courseName": "ML",
    "user": ObjectId("6087dc4c2ba7a828363c9fca"),
    "questions": [  
        {

            "topics": [
               "b"
            ],
        },
        {
            "topics": [
                "b","d"
            ],
        }
    ]
}

Upvotes: 1

Views: 291

Answers (1)

turivishal
turivishal

Reputation: 36154

  • $[] positional for all elements in questions and check condition by $in operator
db.collection.updateMany(
  { 
    "courseName": "ML",
    "user": ObjectId("6087dc4c2ba7a828363c9fca"),
    "questions.topics": { $in: ["a"] } 
  },
  {
    $pull: {
      "questions.$[].topics": { $in: ["a"] }
    }
  }
)

Playground

Upvotes: 2

Related Questions