mongodbHow to order query results in MongoDB?
MongoDB provides the sort()
method to order query results. The sort()
method takes a document as an argument, which contains the field or fields to sort by and the sort order.
Example
db.collection.find().sort({name: 1})
Output example
{ "_id" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"), "name" : "Alice" }
{ "_id" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"), "name" : "Bob" }
{ "_id" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"), "name" : "John" }
Code explanation
db.collection.find()
: This is the command to query the collection.sort({name: 1})
: This is the command to sort the query results. Thename
field is the field to sort by, and1
is the sort order (ascending).
Helpful links
More of Mongodb
- How to check the version of MongoDB?
- How to work with time series data in MongoDB?
- How to use MongoDB queue?
- How to use watch in MongoDB?
- How to join two collections in MongoDB?
- How to drop a database in MongoDB?
- How to specify a password for MongoDB Docker?
- How to update an array element in MongoDB?
- How to use unwind in MongoDB?
- How to use triggers in MongoDB?
See more codes...