如何在查询

时间:2018-03-20 11:50:10

标签: javascript mongodb mongoose mongodb-query aggregate-functions

我正在编写大于等于CREATE_DATE的第一个查询,然后写入CREATE_DATE我得到的答案是计算持续时间写另一个查询但是如何在聚合中编写单个查询。

  

查询1

db.lights.aggregate({
  $match: {
    CREATE_DATE: {
      $gte: ISODate("2018-01-24T20:05:30.000Z"),
      $lt: ISODate("2018-02-24T20:05:30.000Z")
    }
  }
});

结果

{
  "_id": ObjectId("5a9a74843711955836a8b4b5"),
  "SWITCHID": "Z4-W40-SS451A/4",
  "CREATE_DATE": ISODate("2018-01-24T20:05:30Z"),
  "RECEIVEDDATE": ISODate("2018-02-24T20:05:45Z"),
  "STATUS": "LIGHTS ON"
}
  

查询2

db.lights.aggregate([
  {
    $addFields: {
      offduration: {
        $divide: [
          {
            $subtract: [
              "$RECEIVEDDATE",
              "$CREATE_DATE"
            ]
          },
          3600000
        ]
      }
    }
  }
]);

结果

{
  "_id": ObjectId("5a9a75af3711955836a8b4c8"),
  "SWITCHID": "Z4-W40-SS451A/5",
  "CREATE_DATE": ISODate("2018-02-24T20:05:30Z"),
  "RECEIVEDDATE": ISODate("2018-02-24T20:05:45Z"),
  "STATUS": "LIGHTS ON",
  "offduration": 0.004166666666666667
}

1 个答案:

答案 0 :(得分:0)

您需要像这样改进查询:

db.lights.aggregate({
  $match: {
  CREATE_DATE: {
    $gte: ISODate("2018-01-24T20:05:30.000Z"),
    $lt: ISODate("2018-02-24T20:05:30.000Z")
    }
  }
},
 {
  $addFields: {
    offduration: {
      $divide: [
        {
          $subtract: [
            "$RECEIVEDDATE",
            "$CREATE_DATE"
          ]
        },
        3600000
      ]
    }
  }
},
{
$project: {
  _id: 1,
  SWITCHID: 1,
  CREATE_DATE: 1,
  RECEIVEDDATE: 1,
  STATUS: 1,
  offduration: '$offduration',
  avgduration: { $avg: "$offduration" }      
 }
});