Wednesday, January 29, 2014

How to Read or find document (row) in MongoDB?

In this post we will examine how we can read data from MongoDB collection (table). In RDBMS system such as in Oracle, SQL Server, DB2 etc we use SELECT command to read data from table or views.

In MongoDB we have find() method available which we can use to read data.

To read all data from a collection( table) we can use find() method like this.

db.collectioname.find()

To read all the data from deptdetails collection (table) we can write

db.deptdetails.find()

The use of pretty() method with find() method lets the MongoDB show the data in a formatted way.

limit()

If you want to limit the number of records to be return in MongoDB we can use limit(). This is similar to TOP clauses which are used with SELECT command in PL/SQL or T-SQL with RDBMS. The syntax for this is

db.collectioname.find().limit(number)

For example db.deptdetails.find().limit(2).pretty() will show only two documents (row) from deptdetails collection.

sort()

In PL/SQL or T-SQL we use asc or desc to sort the data in a particular order. To read the document (row) in a ascending or descending order we can use sort() method in MongoDB. The syntax for the same is following:

db.collectioname.find().sort({Key:1 or -1})

1 is for ascending order sorting and -1 is for descending order sorting.

Applying condition with find() method.

By default find () method read the entire document (row) of a collection (table). To read specific data or documents which meet your criteria we can apply conditions with find () method.

db.collectioname.find({key1:value1, key2:value2, ... , keyN:valueN})

The below screen shot shows how we can read data from deptdetails collection by applying condition with find() method.

db.deptdetails.find({DeptCode:30,DeptName:"Accounts"}).pretty()

What is MongoDB?
How to get Started with MongoDB
How to create or drop Database in MongoDB?
How to create Collection (Table) in MongoDB?
... More

Popular Posts

Real Time Web Analytics