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
表示降序。