Friday, 20 February 2015

mongodb : Query documents


You can query data by using find() of collection.

Syntax
db.collection.find(<criteria>, <projection>)

Both criteria and projection are optional. Criteria specifies selection criteria using criteria operators. Projection specifies the fields to return using projection operators.

By default, find() returns all the documents in the collection.

> db.employee.find()
{ "_id" : ObjectId("54b2a8c9dbf1847bed465758"), "id" : 1, "firstName" : "Hari Krishna", "lastName" : "Gurram" }
{ "_id" : 2, "firstName" : "Rama Krishna", "lastName" : "Gurram" }
{ "_id" : ObjectId("54b2aa07dbf1847bed465759"), "id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "_id" : ObjectId("54b2aa07dbf1847bed46575a"), "id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "_id" : ObjectId("54b2aa07dbf1847bed46575b"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : ObjectId("54b2aa07dbf1847bed46575c"), "id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }


Use pretty() method to display results in formatted way.

> db.employee.find().pretty()
{
        "_id" : ObjectId("54b2a8c9dbf1847bed465758"),
        "id" : 1,
        "firstName" : "Hari Krishna",
        "lastName" : "Gurram"
}
{ "_id" : 2, "firstName" : "Rama Krishna", "lastName" : "Gurram" }
{
        "_id" : ObjectId("54b2aa07dbf1847bed465759"),
        "id" : 1,
        "firstName" : "Joel",
        "lastName" : "chelli"
}
{
        "_id" : ObjectId("54b2aa07dbf1847bed46575a"),
        "id" : 2,
        "firstName" : "Ananad",
        "lastName" : "Bandaru"
}
{
        "_id" : ObjectId("54b2aa07dbf1847bed46575b"),
        "id" : 3,
        "firstName" : "Gopi",
        "lastName" : "Battu"
}
{
        "_id" : ObjectId("54b2aa07dbf1847bed46575c"),
        "id" : 4,
        "firstName" : "Ritwik",
        "lastName" : "Mohenthy"
}

> db.employee.find({"id":3})
{ "_id" : ObjectId("54b2aa07dbf1847bed46575b"), "id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }


Above snippet gets the document where id is 3. I will explain querying mongoDB in later posts.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment