【问题标题】:How to find output in a collection using max and where condition in mongoDB如何使用 mongoDB 中的 max 和 where 条件在集合中查找输出
【发布时间】:2020-05-09 02:20:01
【问题描述】:

我在这里有一个名为 data 的表,我有一个名为 _id、timeStamp、value 的数据。我需要使用特定日期的 where 条件获取最大值

db.data.aggregate([ { "$group": { "_id": null, "MaximumValue": { "$max": "$value" }}}]);

【问题讨论】:

  • 你能展示你的数据模型和预期输出吗?
  • @mickl 请查看以下模型并考虑时间戳记录为双倍...这不是问题... { "_id" : ObjectId("5e786534018df110a7a2a92f"), "timeStamp" : 1584948532188.0, “价值”:2124 } {“_id”:ObjectId(“5e786534018df110a7a2a930”),“timeStamp”:1584948532288.0,“价值”:231 } {“_id”:ObjectId(“5e786534018df110a7a2a931”),“timeStamp”:8948877: " :4567 }
  • 所以在运行$group 之前,您似乎需要使用$match 作为时间戳,但我需要查看一些示例数据才能回答。基本上$match 成为你的“哪里”。你试过吗?
  • @mickl 谢谢老兄!工作:)
  • 酷,样本数据总是有帮助的:)

标签: mongodb mongoose mongodb-query bson


【解决方案1】:

你可以在运行$group之前使用$match:

db.collection.aggregate([
    { $match: { timeStamp: 1584948532188.0 } },
    { $group: { _id: null, maxVal: { $max: "$value" } } }
])

那么$max 仅应用于过滤的文档集

Mongo Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2018-12-28
    • 2021-08-25
    • 2018-03-14
    • 1970-01-01
    • 2014-08-18
    相关资源
    最近更新 更多