Friday, 20 February 2015

mongoDB : $pop : Removes first/last element of the array


The $pop operator removes the first or last element of an array.

Syntax
{ $pop: { <field>: <-1 | 1>, ... } }

If you pass value -1, then pop removes first elements of the array, if you pass value 1 then pop removes last element of the array.

> db.employee.find()
{ "_id" : 1, "firstName" : "Jessi", "hobbies" : [ "climbing hills" ] }
{ "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies", "climbing hills" ] }
{ "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : 4, "firstName" : "Hari Krishna", "lastName" : "Gurram", "age" : 25 }
{ "_id" : 5, "firstName" : "RamaKrishna", "lastName" : "Amara", "salary" : 150000, "hobbies" : [ "hackning sites", "Reading books", "listening music" ], "age" : 30 }
{ "_id" : 6, "lastName" : "Amara", "age" : 31 }
{ "_id" : ObjectId("54ba2de1f1c8f2149c000740"), "name" : "Krishna", "project" : "A350" }
{ "_id" : ObjectId("54ba2dfcf1c8f2149c000741"), "name" : "Krishna", "project" : 4 }
{ "_id" : ObjectId("54ba47c9f1c8f2149c000742"), "name" : "Keerthi", "hobbies" : [ "watching movies", "playing games", "cooking" ] }


1.Remove last element of array hobbies for employee with id 5.
> db.employee.update({"_id" : 5}, {$pop : {"hobbies" : 1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.employee.find({"_id":5})
{ "_id" : 5, "firstName" : "RamaKrishna", "lastName" : "Amara", "salary" : 150000, "hobbies" : [ "hackning sites", "Reading books" ], "age" : 30 }


2. Remove first element of array hobbies for employee with id 5.
> db.employee.update({"_id" : 5}, {$pop : {"hobbies" : -1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.employee.find({"_id":5})
{ "_id" : 5, "firstName" : "RamaKrishna", "lastName" : "Amara", "salary" : 150000, "hobbies" : [ "Reading books" ], "age" : 30 }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment