特定领域和特定年份的平均值

时间:2019-06-05 16:41:31

标签: mongodb mongodb-query aggregation-framework

我有这样的文件:

db.airportControl.insert({
  identification: "21c3",
  securityGateDate: new Date("2019-06-03T23:00:00Z"),
  boardingDate: new Date("2019-06-03T23:40:00Z"),
  gate: "A21",
  airportDestiny: "LAX"
});
db.airportControl.insert({
  identification: "21c3",
  securityGateDate: new Date("2019-06-04T05:00:00Z"),
  boardingDate: new Date("2018-06-04T05:21:00Z"),
  gate: "A21",
  airportDestiny: "LAX"
});
db.airportControl.insert({
  identification: "21c3",
  securityGateDate: new Date("2019-06-04T07:00:00Z"),
  boardingDate: new Date("2018-06-04T07:41:00Z"),
  gate: "A21",
  airportDestiny: "LAX"
});
db.airportControl.insert({
  identification: "21c3",
  securityGateDate: new Date("2019-06-04T07:00:00Z"),
  boardingDate: new Date("2019-06-04T07:41:00Z"),
  gate: "A21",
  airportDestiny: "TGU"
});

我想知道乘客在机场度过的时间是多少,因为他们经过安检门直到按年和机场登机为止

我有这个查询。我平均得到机场旅客的花费。我又如何才能在特定的年份获得它们?比如说2019:

db.airportControl.aggregate([
  { $match: { airportDestiny: "LAX" } },
  {
    $group: {
      _id: "",
      average: { $avg: { $subtract: ["$boardingDate", "$securityGateDate"] } }
    }
  }
]);

1 个答案:

答案 0 :(得分:2)

您基本上是在要求两个结果,这可以通过使用两个查询或此处类似$facet的方法来实现。

db.collection.aggregate([
  { "$match": { "airportDestiny": "LAX" } },
  { "$facet": {
    "totalAverage": [
      { "$group": {
        "_id": null,
        "average": {
          "$avg": { "$subtract": ["$boardingDate", "$securityGateDate"] }
        }
      }}
    ],
    "averageByYear": [
      { "$match": {
        "$or": [
          { "$expr": { "$eq": [{ "$year": "$boardingDate" }, 2019] }},
          { "$expr": { "$eq": [{ "$year": "$securityGateDate" }, 2019]}}
        ]
      }},
      { "$group": {
        "_id": null,
        "average": {
          "$avg": { "$subtract": ["$boardingDate", "$securityGateDate"] }
        }
      }}
    ]
  }}
])

更新

db.collection.aggregate([
  { "$match": {
    "airportDestiny": "LAX",
    "$or": [
      { "$expr": { "$eq": [{ "$year": "$boardingDate" }, 2019] }},
      { "$expr": { "$eq": [{ "$year": "$securityGateDate" }, 2019] }}
    ]
  }},
  { "$group": {
    "_id": null,
    "average": {
      "$avg": { "$subtract": ["$boardingDate", "$securityGateDate"] }
    }
  }}
])