【问题标题】:Max and min in mongodbMongoDB中的最大值和最小值
【发布时间】:2015-10-19 04:26:30
【问题描述】:

我的条目集合如下:

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

并且有超过 2000 个条目。

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

也许是这样的:

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

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

【问题讨论】:

  • 你的意思是什么它不起作用你有没有收到任何错误信息?
  • 哦,我明白了,我没有使用 _id 作为 null ,它显示了预期的结果谢谢..

标签: mongodb mongodb-query aggregation-framework min


【解决方案1】:

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

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

_id 字段在$group 阶段是强制性的,并且要为孔集合而不是特殊组找到价格的max/min 值,它需要设置为null em> 否则查询将只返回每个组的 max/min

【讨论】:

  • 对于非常大的集合,聚合管道可能会非常慢,因为它会扫描每个文档。如果您需要查找索引字段的最小值/最大值,此处提到的解决方案会更好:stackoverflow.com/a/6360583/3438640 使用带有排序和限制的查找:db.collection.find().sort({price: 1}).limit(1)。
【解决方案2】:

您可以使用$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 上的索引。

【讨论】:

    猜你喜欢
    • 2013-01-03
    • 2021-11-08
    • 2019-02-28
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多