插件窝 干货文章 MongoDB子文档排序:如何使用聚合管道对嵌套数组进行倒序排序?

MongoDB子文档排序:如何使用聚合管道对嵌套数组进行倒序排序?

数组 倒序 items 排序 736    来源:    2025-03-13

在MongoDB中,如果你想要对嵌套在文档中的数组进行倒序排序,可以使用聚合管道中的 $unwind$sort$group 等操作符来实现。以下是一个示例,展示如何对嵌套数组进行倒序排序。

假设你有一个集合 orders,其中每个文档包含一个 items 数组,items 数组中的每个元素是一个子文档,包含 productprice 字段。你想要对每个订单中的 items 数组按照 price 字段进行倒序排序。

示例文档结构

{
  "_id": 1,
  "order_id": "ORD123",
  "items": [
    { "product": "A", "price": 100 },
    { "product": "B", "price": 200 },
    { "product": "C", "price": 50 }
  ]
}

聚合管道操作

  1. $unwind: 将 items 数组展开,使得每个数组元素成为一个独立的文档。
  2. $sort: 对展开后的文档按照 price 字段进行倒序排序。
  3. $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:将排序后的文档重新组合成原来的数组结构,使用 $pushitems 重新组合成一个数组。

通过这种方式,你可以轻松地对嵌套数组进行排序。