【问题标题】:How to use $match in MongoDB如何在 MongoDB 中使用 $match
【发布时间】:2016-12-04 01:32:34
【问题描述】:

所以目前我正在努力从我的查询中获得正确的结果。 这是它的外观:

db.pitching.aggregate([
    { $match: {} },
    { $group: {
        _id: "$playerid",
        maxIpouts: { $max: "$ipouts" }
    }}
])

我知道我必须使用 $match 才能获得正确的结果。我想让一个玩家拥有最高的 ($max) ipout,但我不确定如何使用 $match 进行过滤。

如果没有 $match,它会给我 player_id 和玩家的每个 ipout,而不是具有最高 ipout 的单个玩家 id。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您不需要 $match 管道,您只需将以下管道步骤附加到当前查询(减去 $match)得到你想要的结果。

    $sort - 当您从之前的 $group 管道中获得结果时,您需要按 maxIpouts 字段对文档进行排序,以便您获取具有最多ipouts 排序的文档。

    $limit - 这将为您提供最上面的文档。

    现在,将以上内容组合在一起,您应该运行以下管道以获得所需的结果:

    db.pitching.aggregate([
        {
            "$group": {
                "_id": "$playerid",
                "maxIpouts": { "$max": "ipouts" }
            }
        },
        { "$sort": { "maxIpouts": -1 } },
        { "$limit": 1 } 
    ])
    

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2015-12-28
      • 1970-01-01
      • 2013-12-26
      • 2018-11-25
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      相关资源
      最近更新 更多