Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sorting field value (FirstName) for MongoDB?
To sort field values in MongoDB, use the sort() method with field name and sort direction. Use 1 for ascending order and -1 for descending order.
Syntax
db.collection.find().sort({ "fieldName": 1 }); // Ascending
db.collection.find().sort({ "fieldName": -1 }); // Descending
Sample Data
db.demo365.insertMany([
{ "FirstName": "Chris" },
{ "FirstName": "Adam" },
{ "FirstName": "John" },
{ "FirstName": "Bob" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e57d5b6d0ada61456dc936f"),
ObjectId("5e57d5bad0ada61456dc9370"),
ObjectId("5e57d5bed0ada61456dc9371"),
ObjectId("5e57d5c0d0ada61456dc9372")
]
}
Display all documents from the collection ?
db.demo365.find();
{ "_id": ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName": "Chris" }
{ "_id": ObjectId("5e57d5bad0ada61456dc9370"), "FirstName": "Adam" }
{ "_id": ObjectId("5e57d5bed0ada61456dc9371"), "FirstName": "John" }
{ "_id": ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName": "Bob" }
Example: Sort FirstName in Ascending Order
db.demo365.find().sort({ "FirstName": 1 });
{ "_id": ObjectId("5e57d5bad0ada61456dc9370"), "FirstName": "Adam" }
{ "_id": ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName": "Bob" }
{ "_id": ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName": "Chris" }
{ "_id": ObjectId("5e57d5bed0ada61456dc9371"), "FirstName": "John" }
Example: Sort FirstName in Descending Order
db.demo365.find().sort({ "FirstName": -1 });
{ "_id": ObjectId("5e57d5bed0ada61456dc9371"), "FirstName": "John" }
{ "_id": ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName": "Chris" }
{ "_id": ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName": "Bob" }
{ "_id": ObjectId("5e57d5bad0ada61456dc9370"), "FirstName": "Adam" }
Conclusion
The sort() method arranges documents by specified field values. Use 1 for alphabetical ascending order and -1 for descending order to organize your query results effectively.
Advertisements
