MongoDB sort() 方法
                           
天天向上
发布: 2025-03-07 22:52:33

原创
57 人浏览过

sort() 方法用于对查询结果进行排序,支持升序(1)和降序(-1)排列。通常用于配合 limit()skip() 实现分页查询。


1. 基本排序

升序(1)

按照 price 由小到大排序:

db.products.find().sort({ price: 1 })

降序(-1)

按照 price 由大到小排序:

db.products.find().sort({ price: -1 })

2. 多字段排序

可以按照多个字段排序,优先按照第一个字段排序,如果相同则按照第二个字段排序。

示例

category 升序排列,再按 price 降序排列:

db.products.find().sort({ category: 1, price: -1 })

3. 结合 limit()skip()

通常 sort() 会配合 limit()skip() 进行分页查询,以提高查询效率。

示例

查询 products 集合中的第 2 页数据(每页 5 条),按 price 从高到低排序:

db.products.find().sort({ price: -1 }).skip(5).limit(5)

4. 索引优化 sort() 性能

如果 sort() 字段没有索引,MongoDB 需要在内存中排序,数据量大时会影响性能
可以使用索引提高 sort() 查询效率。

示例

price 字段创建索引:

db.products.createIndex({ price: 1 })

这样 MongoDB 直接使用索引排序,而不会消耗额外内存。


5. sort() 在嵌套文档中的应用

如果文档结构如下:

{
  "_id": 1,
  "name": "Laptop",
  "details": {
    "price": 1200,
    "rating": 4.5
  }
}

按照 details.price 进行排序

db.products.find().sort({ "details.price": 1 })

6. sort()find() 结合

可以在 find() 中使用条件查询,再配合 sort()

示例

查询 price > 50 的商品,并按 price 降序排序:

db.products.find({ price: { $gt: 50 } }).sort({ price: -1 })

7. sort() 在聚合管道(Aggregation)中的使用

aggregate() 方法中,使用 $sort 进行排序。

示例

db.products.aggregate([
  { $match: { category: "electronics" } },  // 先筛选类别
  { $sort: { price: -1 } },  // 按价格降序
  { $limit: 5 }  // 取前 5 个
])

总结

方法作用
sort({ field: 1 })field 升序排列
sort({ field: -1 })field 降序排列
sort({ field1: 1, field2: -1 })先按 field1 升序,再按 field2 降序
find().sort().skip().limit()结合分页查询
createIndex({ field: 1 })建立索引,提高 sort() 性能
$sort (聚合)aggregate() 中排序

更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *