在MongoDB中,如果你想要对嵌套在文档中的数组进行倒序排序,可以使用聚合管道中的 $unwind
、$sort
和 $group
等操作符来实现。以下是一个示例,展示如何对嵌套数组进行倒序排序。
假设你有一个集合 orders
,其中每个文档包含一个 items
数组,items
数组中的每个元素是一个子文档,包含 product
和 price
字段。你想要对每个订单中的 items
数组按照 price
字段进行倒序排序。
{
"_id": 1,
"order_id": "ORD123",
"items": [
{ "product": "A", "price": 100 },
{ "product": "B", "price": 200 },
{ "product": "C", "price": 50 }
]
}
$unwind
: 将 items
数组展开,使得每个数组元素成为一个独立的文档。$sort
: 对展开后的文档按照 price
字段进行倒序排序。$group
: 将排序后的文档重新组合成原来的数组结构。db.orders.aggregate([
// 展开 items 数组
{ $unwind: "$items" },
// 按照 price 字段进行倒序排序
{ $sort: { "items.price": -1 } },
// 重新组合成原来的数组结构
{
$group: {
_id: "$_id",
order_id: { $first: "$order_id" },
items: { $push: "$items" }
}
}
])
执行上述聚合管道后,items
数组将按照 price
字段进行倒序排序。结果如下:
{
"_id": 1,
"order_id": "ORD123",
"items": [
{ "product": "B", "price": 200 },
{ "product": "A", "price": 100 },
{ "product": "C", "price": 50 }
]
}
$unwind
:将 items
数组展开,使得每个数组元素成为一个独立的文档。$sort
:对展开后的文档按照 items.price
字段进行倒序排序(-1
表示倒序)。$group
:将排序后的文档重新组合成原来的数组结构,使用 $push
将 items
重新组合成一个数组。通过这种方式,你可以轻松地对嵌套数组进行排序。