YouTip LogoYouTip

Mongodb Sort

# MongoDB Sorting In MongoDB, use the `sort()` method to sort data. The `sort()` method can specify the field to sort by using parameters, and use `1` and `-1` to specify the sort order, where `1` is for ascending order and `-1` is for descending order. ### Syntax The basic syntax of the `sort()` method is as follows: db.collection.find().sort({ field1: 1, field2: -1 }) * `{ field1: 1, field2: -1 }`: Specifies the fields to sort by and the sort order. `1` indicates ascending order, `-1` indicates descending order. ### Examples Sort by a field in ascending order: ## Example // Sort by age field in ascending order db.myCollection.find().sort({ age:1}); Sort by a field in descending order: ## Example // Sort by createdAt field in descending order db.myCollection.find().sort({ createdAt:-1}); You can specify multiple fields for sorting. MongoDB will sort sequentially according to the specified field order. ## Example // First sort by age field in ascending order, then by createdAt field in descending order db.myCollection.find().sort({ age:1, createdAt:-1}); The data in the `col` collection is as follows: { "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP Tutorial", "description" : "PHP is a powerful server-side scripting language for creating dynamic interactive sites.", "by" : "", "url" : "", "tags" : , "likes" : 200 }{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java Tutorial", "description" : "Java is an advanced programming language launched by Sun Microsystems in May 1995.", "by" : "", "url" : "", "tags" : , "likes" : 150 }{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database", "by" : "", "url" : "", "tags" : , "likes" : 100 } The following example demonstrates sorting the data in the `col` collection by the `likes` field in descending order: >db.col.find({},{"title":1,_id:0}).sort({"likes":-1}){ "title" : "PHP Tutorial" }{ "title" : "Java Tutorial" }{ "title" : "MongoDB Tutorial" }> ### Notes * MongoDB sorts the query results when executing the `sort()` method, which may impact performance. Sorting operations on large datasets can be particularly slow. * If there is an index on the sort field, the sorting operation may be more efficient. When performing frequent sorting operations, consider creating appropriate indexes to improve performance. By using the `sort()` method, you can conveniently sort MongoDB query results to meet different sorting needs and arrange documents in ascending or descending order as required.
← Mongodb IndexingMongodb Limit Skip β†’