You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB集合中对象数组排序:按created字段升降序提取orders

MongoDB 文档内数组排序解决方案

问题场景

我的MongoDB集合中有如下结构的文档:

{
  "_id": "63269e0f85bfd011e989d0f7",
  "name": "Aravind Krishna",
  "mobile": 7309454620,
  "email": "akaravindk59@gmail.com",
  "password": "$2b$12$0dOE/0wj6uX604h3DZpGxuO/L.fZg7KCm7mOGsNMkarSaeG2C/Wvq",
  "orders": [
    {
      "paymentIntentId": "pi_3LjFDtSHVloG65Ul0exLkzsO",
      "cart": [array],
      "amount": 3007,
      "created": 1663475717,
      "_id": "6326a01344f26617fc1a65d6"
    },
    {
      "paymentIntentId": "pi_3LjFFUSHVloG65Ul1FQHlZ9H",
      "cart": [array],
      "amount": 389,
      "created": 1663475816,
      "_id": "6326a07744f26617fc1a65d8"
    }
  ],
  "__v": 0
}

需要仅获取_id和orders字段,同时将orders数组按created字段分别做升序、降序排序,尝试sortArray方法时出现报错,求可行方案。

预期输出示例(升序):

{
  "_id": "63269e0f85bfd011e989d0f7",
  "orders": [
    {
      "paymentIntentId": "pi_3LjFDtSHVloG65Ul0exLkzsO",
      "cart": [array],
      "amount": 3007,
      "created": 1663475717,
      "_id": "6326a01344f26617fc1a65d6"
    },
    {
      "paymentIntentId": "pi_3LjFFUSHVloG65Ul1FQHlZ9H",
      "cart": [array],
      "amount": 389,
      "created": 1663475816,
      "_id": "6326a07744f26617fc1a65d8"
    }
  ]
}

解决方案

方法1:使用$sortArray(MongoDB 5.2+ 版本)

如果你的MongoDB版本是5.2及以上,$sortArray是最直接的方式,报错大概率是语法问题,正确写法如下:

升序排序

db.collection.aggregate([
  // 只保留_id和orders字段
  { $project: { orders: 1 } },
  // 对orders数组按created升序排序
  { $project: {
      orders: {
        $sortArray: {
          input: "$orders",
          sortBy: { created: 1 }
        }
      }
    }
  }
])

降序排序

仅需修改sortBy内created的取值为-1:

db.collection.aggregate([
  { $project: { orders: 1 } },
  { $project: {
      orders: {
        $sortArray: {
          input: "$orders",
          sortBy: { created: -1 }
        }
      }
    }
  }
])

方法2:兼容低版本的聚合方案(MongoDB 5.2以下适用)

若MongoDB版本不支持$sortArray,可通过$unwind+$sort+$group的组合实现需求:

升序排序

db.collection.aggregate([
  // 只保留需要的字段
  { $project: { orders: 1 } },
  // 拆分orders数组
  { $unwind: "$orders" },
  // 按created升序排序
  { $sort: { "orders.created": 1 } },
  // 重新组合成数组
  { $group: {
      _id: "$_id",
      orders: { $push: "$orders" }
    }
  }
])

降序排序

将$sort内"orders.created"的取值改为-1即可:

db.collection.aggregate([
  { $project: { orders: 1 } },
  { $unwind: "$orders" },
  { $sort: { "orders.created": -1 } },
  { $group: {
      _id: "$_id",
      orders: { $push: "$orders" }
    }
  }
])

说明

  • 方法1执行效率更高,适合高版本MongoDB;方法2兼容性更强,适配低版本环境。
  • 两种方案都能精准返回_id和排序后的orders数组,完全匹配预期输出要求。

内容的提问来源于stack exchange,提问作者Aravind Krishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:25:29