如何在Node.js中基于UserId获取匹配的聚合

时间:2018-02-13 13:20:04

标签: javascript node.js mongodb reactjs aggregation-framework

我正在研究示例应用程序,因为我使用了聚合,我实现了一个基于用户ID匹配从其获取MAXDate和MINDate的状态的查询。如何根据最大和最小字段获取剩余字段。

    app.get('/varun', function (req, res) {
  Light.aggregate( [ 
      { 
      "$match" : {
             "STATUS":"LIGHTS OFF"} 
      },
        {
         "$group" : {
                "_id" : "$SWITCHID",
                    LIGHTOFFMINDATE: { "$min" : "$RECEIVEDDATE"
                                      },
                    LIGHTOFFMAXDATE:{"$max":"$RECEIVEDDATE"
                                    },
                    information:{"$push":
                    {
                      _id:"$SWITCHID",
                      TOTALSTREETLIGHTS:"$TOTALSTREETLIGHTS",
                      WORKINGSTREETLIGHTS:"$WORKINGSTREETLIGHTS",
                      CUMULATIVEKWH:"$CUMULATIVEKWH",
                      STATUS:"$STATUS",
                      LATITUDE:"$LATITUDE",
                      LONGITUDE:"$LONGITUDE",
                      OFFICE_ID:"$OFFICE_ID",
                      FLAG2:"$FLAG2",
                      CREATE_DATE:"$CREATE_DATE"

                    }
                  },
},

}]
, function (err, light) {

  console.log("naresh:" +JSON.stringify(light));


        res.json(light);
    });
});

output:-
"_id": "Z6-W66-9C/3",
        "LIGHTOFFMINDATE": "2018-02-09T00:00:00.000Z",
        "LIGHTOFFMAXDATE": "2019-02-09T00:00:00.000Z",

在这里,我将代码与相关的输出放在一起。任何人都建议我如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

尝试在$sort之前添加$group,并使用$first$last$$ROOT一起访问整个文档。

Light.aggregate([
  {"$match":{"STATUS":"LIGHTS OFF"}},
  {"$sort":{"RECEIVEDDATE":1}},
  {"$group":{
    "_id":"$SWITCHID",
    "LIGHTOFFMINDATE":{"$first":"$$ROOT"},
    "LIGHTOFFMAXDATE":{"$last":"$$ROOT"}
  }}
],function (err, light) {
   console.log("naresh:" +JSON.stringify(light));
   res.json(light);
});

获取最小和最大日期的计数

Light.aggregate([
  {"$match":{"STATUS":"LIGHTS OFF"}},
  {"$sort":{"RECEIVEDDATE":1}},
  {"$group":{
    "_id":"$SWITCHID",
    "LIGHTOFFMINDATEDOC":{"$first":"$$ROOT"},
    "LIGHTOFFMAXDATEDOC":{"$last":"$$ROOT"},
    "ALLDOCS":{"$push":"$$ROOT"}
  }},
  {"$project": {
    "LIGHTOFFMINDATEDOC": 1,
    "minSalary": 1,
    "LIGHTOFFMAXDATEDOC": 1,
    "LIGHTOFFMINDATECOUNT": {
      "$size": {
        "$filter": {
          "input": "$ALLDOCS",
          "as": "doc",
          "cond": {
            "$eq": [
              "$$doc.RECEIVEDDATE",
              "$LIGHTOFFMINDATEDOC.RECEIVEDDATE"
            ]
          }
        }
      }
    },
    "LIGHTOFFMAXDATECOUNT": {
      "$size": {
        "$filter": {
          "input": "$ALLDOCS",
          "as": "doc",
          "cond": {
            "$eq": [
              "$$doc.RECEIVEDDATE",
              "$LIGHTOFFMAXDATEDOC.RECEIVEDDATE"
            ]
          }
        }
      }
    }
  }}
],function (err, light) {
    console.log("naresh:" +JSON.stringify(light));
    res.json(light);
});