sort() - ( Querying and Projection )
In MongoDB, the sort()
method is used to sort the documents in a collection based on a specific field. This method is part of the Querying and Projection operations.
Syntax
The sort()
method takes one parameter, which is an object that specifies the field to sort on and the order of the sorting:
db.collection.find().sort({ field: order });
The field
parameter is the name of the field to sort on, and order
is the order in which the documents should be arranged. There are two options for the order parameter: 1
for ascending order and -1
for descending order.
Example
Suppose we have a collection employees
with the following documents:
{ Name: "John", Age: 25, Department: "IT" }
{ Name: "Alice", Age: 32, Department: "HR" }
{ Name: "Bob", Age: 28, Department: "Finance" }
To sort this collection in ascending order based on the Age
field, we can use the following statement:
db.employees.find().sort({ Age: 1 });
The result of this query will be:
{ Name: "John", Age: 25, Department: "IT" }
{ Name: "Bob", Age: 28, Department: "Finance" }
{ Name: "Alice", Age: 32, Department: "HR" }
To sort in descending order:
db.employees.find().sort({ Age: -1 });
The result of this query will be:
{ Name: "Alice", Age: 32, Department: "HR" }
{ Name: "Bob", Age: 28, Department: "Finance" }
{ Name: "John", Age: 25, Department: "IT" }
Output
The sort()
method returns a cursor object, which can be iterated to access the documents in the sorted order.
Explanation
The sort()
method in MongoDB sorts the documents in a collection based on the specified field and order. It is useful for querying documents in a specific order.
Use
The sort()
method is used to sort the documents in a collection. This method is useful in situations where you need to retrieve documents in a particular order, such as age, date, score, etc.
Important Points
- The
sort()
method is used to sort the documents in a collection. - Only one field can be used to sort the documents.
- The
sort()
method can be used in combination with other query operators.
Summary
In this page, we discussed the sort()
method in MongoDB, which is used to sort the documents in a collection. We covered the syntax, example, output, explanation, use, and important points of the sort()
method. By using the sort()
method, you can retrieve documents from a collection in a specific order based on a particular field.