【问题标题】:MongoDB query using aggregation not returning expected results使用聚合的 MongoDB 查询未返回预期结果
【发布时间】:2014-10-19 11:33:55
【问题描述】:

我有一些看起来像这个例子的文档:

{
  "_id": ObjectId("540f4b6496f35c16af001dc4"),
  "groups": [
    1,
    46105,
    46106,
    53241,
    55397,
    55406,
    62840
  ],
  "vehicleid": 123,
  "vehiclename": "123 - CAN BC",
  "totaldistancetraveled": 472.0,
  "date_num": 20140901
}

我需要找到属于组 46105 的所有车辆行驶的总距离,并且 date_num 与 20140901 匹配。

我尝试了以下聚合查询:

db.vehicle_performance_monthly.aggregate(
           { $unwind : "$groups"},
           {$group:
           {_id: "$groups",           
           totalMiles: { $sum: "$totaldistancetraveled"}}},
           {$match:{_id: {$in:[46106]}},{"$date_num":{$in:20140901}}}
           )

但没有返回多个匹配项。任何帮助表示赞赏。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    这应该可以。

    db.vehicle_performance_monthly.aggregate([ {
        $match : {
            groups : 46106,
            date_num : 20140901
        }
    }, {
        $unwind : "$groups"
    }, {
        $match : {
            groups : 46106
        }
    }, {
        $group : {
            _id : "$groups",
            totalMiles : {
                $sum : "$totaldistancetraveled"
            }
        }
    } ]);
    

    分析您的原始答案:

    db.vehicle_performance_monthly.aggregate(
           { $unwind : "$groups"},
           {$group:
           {_id: "$groups",           
           totalMiles: { $sum: "$totaldistancetraveled"}}},  // $group doesn't map "date_name" then it will lost.
           {$match:{_id: {$in:[46106]}},{"$date_num":{$in:20140901}}} // syntax error: {$match:{_id: {$in:[46106]}},{"$date_num":{$in:20140901}}}  should be   {$match:{_id: {$in:[46106]},"$date_num":{$in:[20140901]}}}
           )
    

    $match first 以提高性能

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多