Friday 20 February 2015

mongoDb : $pull : Removes value or values that match query from array


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

Syntax
{ $pull: { <field1>: <value|query>, ... } }

Let’s say I had below data.

db.sample.insert([
  {
    "_id" : 1,
    "arr" : [1,2,3,4,5,6,7,8,9]
  },
  {
    "_id" : 2,
    "arr" : [9,8,7,6,5,4,3,2,1]
  },
  {
    "_id" : 3,
    "arr" : [19,28,37,6,55,14,32,28,61]
  },
  {
    "_id" : 4,
    "arr" : [109,208,3,6,5,104,302,280,161]
  },
  {
    "_id" : 5, 
    "arr" : [1,7,6,7,5,5,4]
  }
])

> db.sample.find()
{ "_id" : 1, "arr" : [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] }
{ "_id" : 2, "arr" : [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ] }
{ "_id" : 3, "arr" : [ 19, 28, 37, 6, 55, 14, 32, 28, 61 ] }
{ "_id" : 4, "arr" : [ 109, 208, 3, 6, 5, 104, 302, 280, 161 ] }
{ "_id" : 5, "arr" : [ 1, 7, 6, 7, 5, 5, 4 ] }


1.Remove element 7 from document with id 5.

> db.sample.update({"_id" : 5}, {$pull : {"arr" : 7}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.sample.find({"_id": 5})
{ "_id" : 5, "arr" : [ 1, 6, 5, 5, 4 ] }


As you observe document with id 5 has entry 7 twice, after pulling 7 it removed at 2 places.

2.Remove all the elements from document 3 where value > 20
> db.sample.update({"_id" : 5}, {$pull : {"arr" : 7}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.sample.find({"_id": 5})
{ "_id" : 5, "arr" : [ 1, 6, 5, 5, 4 ] }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment