Friday 20 February 2015

Querying using field selection


You can ask mongoDb, to retrieve the documents that satisfy given field values.

> db.employee.find()
{ "_id" : ObjectId("54b9485dfda21cabf10932cd"), "id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "_id" : ObjectId("54b9485dfda21cabf10932ce"), "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "_id" : ObjectId("54b9485dfda21cabf10932cf"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : ObjectId("54b9485dfda21cabf10932d0"), "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }
{ "_id" : ObjectId("54b94c26fda21cabf10932d1"), "firstName" : "Hari", "lastName" : "Krishna" }
{ "_id" : ObjectId("54b94c2cfda21cabf10932d2"), "firstName" : "Rama", "lastName" : "Krishna" }
{ "_id" : ObjectId("54b94c32fda21cabf10932d3"), "firstName" : "Murali", "lastName" : "Krishna" }
>


To retrieve all the documents where lastname is “Krishna”
> db.employee.find({"lastName" : "Krishna"})
{ "_id" : ObjectId("54b94c26fda21cabf10932d1"), "firstName" : "Hari", "lastName" : "Krishna" }
{ "_id" : ObjectId("54b94c2cfda21cabf10932d2"), "firstName" : "Rama", "lastName" : "Krishna" }
{ "_id" : ObjectId("54b94c32fda21cabf10932d3"), "firstName" : "Murali", "lastName" : "Krishna" }


To retrieve all the documents where firstName is “Hari” and lastName is “Krishna”.

> db.employee.find({"firstName" : "Hari", "lastName" : "Krishna"})
{ "_id" : ObjectId("54b94c26fda21cabf10932d1"), "firstName" : "Hari", "lastName" : "Krishna" }


To retrieve all the documents where firstName is “Hari” and lastName is “Krishna” and get only field firstName.
> db.employee.find({"firstName" : "Hari", "lastName" : "Krishna"}, {"firstName":true, "_id":false})
{ "firstName" : "Hari" }

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment