【问题标题】:MongoDb aggregation framework value of a field where max another field一个字段的 MongoDb 聚合框架值,其中 max 另一个字段
【发布时间】:2015-03-15 00:18:47
【问题描述】:

我有一个包含如下记录的集合:

"_id" : ObjectId("550424ef2f44472856286d56"), "accountId" : "123", 
"contactOperations" :
    [
        { "contactId" : "1", "operation" : 1, "date" : 500 },
        { "contactId" : "1", "operation" : 2, "date" : 501 },
        { "contactId" : "2", "operation" : 1, "date" : 502 } 
    ] 
}

我想知道某个联系人最近申请的操作号。

我使用聚合框架首先展开contactOperations,然后按accountId和contactOperations.contactId和max contactOperations.date进行分组。

aggregate([{$unwind : "$contactOperations"}, {$group : {"_id":{"accountId":"$accountId", "contactId":"$contactOperations.contactId"}, "date":{$max:"$contactOperations.date"} }}])

我得到的结果是:

"_id" : { "accountId" : "123", "contactId" : "2" }, "time" : 502 }
"_id" : { "accountId" : "123", "contactId" : "1" }, "time" : 501 }

到目前为止这似乎是正确的,但我还需要使用 $max 日期记录的 contactOperations.operation 字段。我该如何选择?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您必须对展开值进行排序,然后应用 $last 运算符来获取最大日期的操作。希望此查询能解决您的问题。

    aggregate([
      {
        $unwind: "$contactOperations"
      },
      {
        $sort: {
          "date": 1
        }
      },
      {
        $group: {
          "_id": {
            "accountId": "$accountId",
            "contactId": "$contactOperations.contactId"
          },
          "date": {
            $max: "$contactOperations.date"
          },
          "operationId": {
            $last: "$contactOperations.operation"
          }
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 2013-07-23
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多