管道阶段中的MongoDB错误对象

时间:2016-12-02 00:35:43

标签: mongodb match aggregation-framework

我正在尝试计算每月的平均航班但我收到错误

“管道阶段规范对象必须只包含一个字段。”,

db.Flights.aggregate([
{$unwind: "$flights"},
{$project: 
    {_id: 0,
    status: 1,
    flights: 1
},

$match: {"status": "active"},
$group: {_id: {"flights" : "$flights.flight_id", "Month":       "$depart_info.month_name_long"}, 
avg_flights: {$avg: "$flights.count"}}}

])

1 个答案:

答案 0 :(得分:0)

您的汇总管道有些格格不入;特别是$ match和$ group阶段。每个阶段都需要是一个JSON文档。请尝试以下方法:

db.Flights.aggregate([
  {
      $unwind: "$flights"
  }, 
  {
    $project: {
      _id: 0,
      status: 1,
      flights: 1
    },
  },
  {
    $match: {
      "status": "active"
    }
  },
  {
    $group: {
      _id: {
          "flights": "$flights.flight_id",
          "Month": "$depart_info.month_name_long"
      },
      avg_flights: {
          $avg: "$flights.count"
      }
    }
  }
])