MongoDB 聚合 $sort
聚合 $sort
此聚合阶段按指定的排序顺序对所有文档进行排序。
请记住,您各个阶段的顺序很重要。每个阶段仅对前一个阶段提供的文档进行操作。
示例
In this example, we are using the "sample_airbnb" database loaded from our sample data in the Intro to Aggregations section. (在此示例中,我们使用的是在“聚合入门”部分的示例数据中加载的“sample_airbnb”数据库。)
db.listingsAndReviews.aggregate([
{
$sort: { "accommodates": -1 }
},
{
$project: {
"name": 1,
"accommodates": 1
}
},
{
$limit: 5
}
])
自己动手试一试 »
这将按 accommodates
字段的降序返回文档。
可以使用 1
或 -1
选择排序顺序。1
表示升序,-1
表示降序。