Friday 20 February 2015

mongoDB : $push : Appends value to array


$push operator is used to append value to array.

Syntax
{ $push: { <field1>: <value1>, ... }

> db.employee.find()
{ "_id" : 1, "firstName" : "Jessi" }
{ "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies" ] }
{ "_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.Add hobby “climbing hills” to employee with id 2.
> db.employee.update({"_id" : 2}, {$push : {"hobbies" : "climbing hills"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.employee.find({"_id" : 2})
{ "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru", "salary" : 200000, "hobbies" : [ "car drivinig", "watching movies", "climbing hills" ] }


If the field is absent in the document to update, $push adds the array field with the value as its element.

2. Add hobby “climbing hills” to employee with id 1.
> db.employee.find({"_id":1})
{ "_id" : 1, "firstName" : "Jessi" }
>
> db.employee.update({"_id" : 1}, {$push : {"hobbies" : "climbing hills"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.employee.find({"_id":1})
{ "_id" : 1, "firstName" : "Jessi", "hobbies" : [ "climbing hills" ] }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment