OPTIONS

$pull

$pull

The $pull operator removes from an existing array all instances of a value or values that match a specified query.

db.collection.update( <query>,
                      { $pull: { <arrayField>: <query2> } }
                    )

Examples

Remove All Items That Equals a Specified Value

Given the following documents in the cpuinfo collection:

{ _id: 1, flags: [ "vme", "de", "msr", "tsc", "pse", "msr" ] }
{ _id: 2, flags: [ "msr", "pse", "tsc" ] }

The following operation removes the value "msr" from the flags array:

db.cpuinfo.update(
                   { flags: "msr" },
                   { $pull: { flags: "msr" } },
                   { multi: true }
                 )

After the operation, the documents no longer contain any "msr" values in the flags array:

{ _id: 1, flags: [  "vme",  "de",  "tsc",  "pse" ] }
{ _id: 2, flags: [  "pse",  "tsc" ] }

Remove All Items Greater Than a Specified Value

Given the following document in the profiles collection:

{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }

The following operation will remove all items from the votes array that are greater than or equal to ($gte) 6:

db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )

After the update operation, the document only has values less than 6:

{ _id: 1, votes: [  3,  5 ] }

Remove Items from an Array of Documents

Given the following documents in the survey collection:

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "ijk", score: 7 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "ijk", score: 7 }, { product: "eft", score: 10 } ] }

The following operation will remove from the results array all elements that contain a score field whose value is greater than or equal to ($gte) 8:

db.survey.update(
  { "results.score": { $gte: 8 } },
  { $pull: { results: { score: { $gte: 8 } } } },
  { multi: true }
)

After the operation, the results array contains no documents with score greater than or equal to 8:

{ "_id" : 1, "results" : [ { "product" : "xyz", "score" : 5 } ] }
{ "_id" : 2, "results" : [ { "product" : "ijk", "score" : 7 }, { "product" : "xyz", "score" : 7 } ] }
{ "_id" : 3, "results" : [ { "product" : "ijk", "score" : 7 } ] }
←   $pullAll $pushAll  →