首页 > 解决方案 > mongo中的最小嵌套数组

问题描述

如何使用 $min 函数获取嵌套数组中的最小值(并将其添加到文档中)?

[
  {
    "_id": "a357e77f-a76a-4bc2-8765-923280663e97",
    "customers": [
      {
        "_id": "97170117-4660-4c6f-b8da-2b34d4d0c9ce",
        "orders": [
          {
            "amount": 0.5
          },
          {
            "amount": 6.400001525878906
          }
        ]
      },
      {
        "_id": "7b9ccf5b-3acb-4ed1-8df4-e3b5afc49cba",
        "orders": [
          {
            "amount": 27.29999542236328
          },
          {
            "amount": 0.29999542236328125
          }
        ]
      }
    ]
  },
  {
    "_id": "58433224-8162-4f0a-8168-bc11b4306b0a",
    "customers": [
      {
        "_id": "8a6055d0-9b94-40be-8f96-8fd9088d24aa",
        "orders": [
          {
            "amount": 19.700000762939453
          }
        ]
      },
      {
        "_id": "a50a57b8-61e7-4727-a15a-4a4137b2f81a",
        "orders": [
          {
            "amount": 43.80000305175781
          }
        ]
      }
    ]
  }
]

如何获取 $customers.orders.amount 路径中的最小金额值?

我试过了,但它返回 0。

db.collection.aggregate([
  {
    $addFields: {
      "amount": {
        $sum: "$customers.orders.amount"
      }
    }
  }
])

标签: mongodb

解决方案


您可以为每个客户执行以下操作

操场

db.collection.aggregate([
  {//Destruct
    "$unwind": "$customers"
  },
  {//Destruct
    "$unwind": "$customers.orders"
  },
  {//Group by customer id,
    $group: {
      "_id": "$customers._id",
      min: {
        $push: {
          "$min": "$customers.orders.amount"
        }
      }
    }
  }
])

group by null如果您想在所有客户中找到最小值,则可以使用。


推荐阅读