mongodb 中的最大值和最小值

Max and min in mongodb

我有如下条目集合:

{
  company:"C3",
  model:"M3",
  price:55600,
  discount:9,
  ...
}

并且有超过 2000 个条目。

我正在尝试找出整个系列中的 max min 价格。

也许与以下内容类似:

db.collection.find({ max: { $max: "$price" }, min: { $min: "$price" } });

我希望输出为 { max: 2000, min: 5000 }

您需要使用 .aggregate() 方法才能正常工作。

db.collection.aggregate([ 
    { "$group": { 
        "_id": null,
        "max": { "$max": "$price" }, 
        "min": { "$min": "$price" } 
    }}
])

_id 字段在 $group stage and to find the max/min 值中是强制性的,用于孔集合的价格而不是特殊组,它需要设置为 null 否则查询只会 return max/min 每个组

您可以使用 $facet 阶段,结合 $sort/$limit 阶段:

// { "price": 123 }
// { "price": 165 }
// { "price": 98  }
// { "price": 34  }
db.collection.aggregate([
  { $facet: {
    min: [{ $sort: { price:  1 } }, { $limit: 1 }],
    max: [{ $sort: { price: -1 } }, { $limit: 1 }]
  }},
  { $project: { min: { $first: "$min.price" }, max: { $first: "$max.price" } } }
])
// { "min" : 34, "max" : 165 }

$facet 阶段允许我们在同一个输入文档集上的单个阶段中 运行 多个聚合管道。每个子管道在输出文档中都有自己的字段,其结果存储为文档数组。

因此,每个字段都由其自己的聚合管道生成,其第一阶段 $sorts 按指定顺序定价,然后是 $limit 阶段,该阶段仅保留第一个项目(最小的由所选顺序定义)。

管道的第二部分($set 阶段)用于将 $facet 输出清理为您希望的格式。


请注意,$sort 后跟 $limit 阶段由 Mongo 优化(参见 here)。这允许排序操作在进行时仅保留前 n 个结果(在我们的例子中只有 1 个元素)。

另请注意,我们的 $sort 阶段将受益于 price 上的索引。