Pull elements from array - how?

I’ve been reading through the documentation on $pull, $elemMatch and arrayFilters but can’t seem to find the right way to pull elements from an array.

Given this initial data:

db.survey.insertMany([
   {
      _id: 1,
      results: [
         { item: "A", score: 5 },
         { item: "B", score: 8 }
      ]
   },
   {
      _id: 2,
      results: [
         { item: "C", score: 8 },
         { item: "B", score: 4 }
      ]
   }
] )

And let’s say we want to pull (remove) elements from the results array in all documents - where the score is less than or equal to 4.

According to the documentation this would seem like the right way:

db.survey.updateMany(
  { },
  { $pull: { results: { $elemMatch: { score: { $lte: 4 } } } } }
  )

But this doesn’t do the trick. Result as follows:

{ acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 0,
  upsertedCount: 0 }

Appreciate any help on the matter.

Hi :wave: @Kristoffer_Almas,

Welcome back to the Community forums :sparkles:

To remove elements from a collection using the $pull operator, you don’t need to use the $elemMatch operator. This is because $pull treats each element as a top-level object and applies the query to each element individually. Therefore, you can simply specify the match conditions in the expression without using $elemMatch.

If you do use $elemMatch, the $pull operation will not remove any elements from the original collection.

Here’s an updated version of your query without $elemMatch:

db.survey.updateMany(
  {},
  { $pull: { results: { score: { $lte: 4 } } } }
)

And it will return the following output:

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

For more information, please refer to the $pull - Remove Items from an Array of Documents documentation.

I hope it helps.

Regards,
Kushagra

1 Like