Using $pull in Mongodb aggregation pipelines

Removing a value from existing array using $pull

Suppose we have the following documents in the users collection:

{
"_id": 1,
"user_name": "sujaykundu",
"email": "[email protected]",
"sports": ["cricket", "football", "swimming"]
},
{
"_id": 2,
"user_name": "johndoe",
"email": "[email protected],
"sports" ["webdev", "swimming"]
}

Now, if I want to delete swimming from the document where the user_name is “sujaykundu”

we can do is :

db.users.update(
     { "user_name": "sujaykundu" },
     {
       $pull: {
         sports: {
                $in : ["swimming", "football" ]
          }
       },
      {
       multi: true
      }
)

Now, the result will be:

{
 "_id": 1,
 "user_name": "sujaykundu",
 "email": "[email protected]",
  "sports": ["cricket"]
},
{
  "_id": 2,
  "user_name": "johndoe",
  "email": "[email protected],
   "sports" ["webdev", "swimming"]
}

### Remove Items from an Array of embedded documents

Now suppose we had the documents which has array of embedded documents,

A survey collection contains the following documents:

{
   _id: 1,
  results: [
         { item: "A", score: 5 },
        { item: "B", score: 8, comment: "Strongly agree" }
   ]
},
{
   _id: 2,
   results: [
        { item: "C", score: 8, comment: "Strongly agree" },
       { item: "B", score: 4 }
   ]
}

Now if we want to remove documents that have score as 8 and item field as B,
we can do the following :

db.users.update(
  { "user_name": "sujaykundu" },
  { 
     $pull : {
    "results": { score: 8, item: "B" }
     },
     {
         multi :true
     }
  }
)

then the result will be like this:

{
"_id" : 1,
"results" : [ { "item" : "A", "score" : 5 } ]
}
{
"_id" : 2,
"results" : [
{ "item" : "C", "score" : 8, "comment" : "Strongly agree" },
{ "item" : "B", "score" : 4 }
]
}

### Remove Items from an Array of embedded documents that also contains arrays

suppose we have this :


{
_id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
{ item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ] }
]
}
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ] },
{ item: "B", score: 4, answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ] }
]
}

Then you can specify multiple conditions on the elements of the answers array with $elemMatch:

db.survey.update(
{ },
{ $pull: { results: { answers: { $elemMatch: { q: 2, a: { $gte: 8 } } } } } },
{ multi: true }
)

The operation removed from the results array those embedded documents with an answers field that contained at least one element with q equal to 2 and a greater than or equal to 8:


{
"_id" : 1,
"results" : [
{ "item" : "A", "score" : 5, "answers" : [ { "q" : 1, "a" : 4 }, { "q" : 2, "a" : 6 } ] }
]
}
{
"_id" : 2,
"results" : [
{ "item" : "C", "score" : 8, "answers" : [ { "q" : 1, "a" : 8 }, { "q" : 2, "a" : 7 } ] }
]
}

So that was $pull in mongodb aggregation

Scroll to Top