In Node.js, To sort, skip and limit data in MongoDB, we can use the "sort()", "skip()" and "limit()" methods in conjunction with our query.
These methods allow us to control the order of documents returned by a "query" and "limit" the number of documents returned.
To sort data in MongoDB, we can use the "sort()" method, passing an object specifying the fields to sort by and their respective order (ascending or descending).
We can sort fields by passing multiple key-value pairs to the "sort()" method in ascending order.
db.employees.find().sort({ name: 1 })
We can sort fields by passing multiple key-value pairs to the "sort()" method in descending order.
db.employees.find().sort({ name: -1 })
To limit the number of documents returned by a query in MongoDB, we can use the "limit()" method.
This method takes a number specifying the maximum number of documents to return.
db.employees.find().limit(20)
This will return the first 20 documents matching the query criteria.
We can combine the "sort()" and "limit()" methods to control both the order and the number of documents returned by a query.
db.employees.find().sort({ name: 1, age: -1 }).limit(10)
This will return the 10 documents with the "name" in ascending order and the "age" in descending order.
We can combine the "sort()", "skip()" and "limit()" methods to control the order and the number of documents returned by a query. skip and limit are often used for pagination when there are lots of records in the collections to be displayed on the User Interface.
// we can keep `limit` value as constant // in initial we will send skip 0. so it will fetch first 20 records. -> 1 to 20 db.employees.find().sort({ name: 1 }).limit(20).skip(0); // in next call we can send skip 20. so it will fetch next 20 records. -> 21 to 40. // it will skip first 20 records. db.employees.find().sort({ name: 1 }).limit(20).skip(20);
we can achieve the same functionality using the "sort()", "skip()" and "limit()" methods provided by Mongoose models.
EmployeeModel.find().sort({ name: 1, age: -1 }).limit(10).skip(0) .then((users) => { console.log('Fetch Sorted and limited users successfully: ', users); }) .catch((err) => { console.error('Error while sorting and limiting users:', err); });
This will asynchronously find and return the 10 documents with the "name" in ascending order and the "age" in descending order from the "Employee" collection.