MongoDB Read
Read operations or queries, fetch data in the database. In MongoDB, queries select document from a single collection. The queries are like other database queries that specify the condition to fetch the data from the database.
Query:
In MongoDB find() method accepts both query criteria and projection to fetch the records.
Example:
db.employees.find( { _id: 1 } , { firstName: true , lastName: true , phone: true , email: true });
Below query is the equivalent SQL query.
SELECT _id, firstName, lastName, phone, email FROM employees WHERE _id = 1
Sorting:
The order of the results by a query is not not defined. If you need the result set in a order you need to specify the order. To apply sorting to the result set use sort() method. It accepts a field and sort order. Specify in the sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively.
Example:
db.employees.find().sort({modAt: -1}) // Descending order db.employees.find().sort({modAt: 1}) // Ascending order
SQL comparison
SELECT * FROM Employees ORDER BY ModAt DESC SELECT * FROM Employees ORDER BY ModAt ASC
Limit:
Use of limit() method on a cursor to specify the maximum no of records. It's equivalent in SQL server is TOP
Example:
db.employees.find().limit(5)
SQL comparison
SELECT TOP 5 * FROM Employees
Skip:
We can use the skip method to control where MongoDB starts fetching records. It is mainly used for paged results like pagination.
Example:
var pageNumber = 2, pageLimit = 5, skipNumber = (pageNumber – 1) * pageLimit; db.employees.find().skip( skipNumber).limit(pageLimit);
The above query returns the records for second page. It will skip first 5 records and will fetch second 5 records.
Conclusion:
In this tutorial, I have explained the basics of read operations on MongoDB. I will add more in my next articles.
Reference: