Friday 20 February 2015

mongoDB : Upserts


It is an option used in update query. If set to true, the update operation will either update the first document matched by a query or insert a new document if none matches.

> 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" : 6, "lastName" : "Amara", "age" : 31 }
>
>
> db.employee.update({"firstName" : "Murthy"}, {$set : {"lastName" : "Krishna", "age" : 30}}, {"upsert" : true})
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 1,
        "nModified" : 0,
        "_id" : ObjectId("54ba9242f048afaff2a00317")
})
>
> 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" : 6, "lastName" : "Amara", "age" : 31 }
{ "_id" : ObjectId("54ba9242f048afaff2a00317"), "firstName" : "Murthy", "lastName" : "Krishna", "age" : 30 }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment