首页 > 解决方案 > 聚合嵌套数组元素

问题描述

我在聚合方面遇到了麻烦。我有这些字段的集合“站”:

stationName: string,
systemName: string,
commodities:[{
    name: string,
    buyPrice: number,
    sellPrice: number,
    stock: number,
    demand: number
}]

我需要查询特定商品的最高最低价格。例如:我有商品“水”,需要在所有站点条目中获得最高的 sellPrice。

提前致谢

标签: mongodbaggregation-framework

解决方案


您可以尝试使用/进行aggregate查询,$max$min

db.collection.aggregate([
  {
    $project: {
      stationName: true,
      systemName: true,
      maxBuyPrice: {
        $max: "$commodities.buyPrice"
      },
      maxSellPrice: {
        $max: "$commodities.sellPrice"
      },
    }
  }
])

蒙哥游乐场

对于最低价格,您可以在查询中替换$max$min,或者如果这是您想要的,则包括两者


推荐阅读