Thursday 20 April 2017

Node.js calling MongoDB with aggregate find

I have used SQL Server for a long time and just really learning MongoDB. I am trying to figure out how to do the aggregate finds to get just the data I want. Here is a sample from the database:

{
  "_id": "1",
  "user_id": "123-88",
  "department_id": "1",
  "type": "start",
  "time": "2017-04-20T19:40:15.329Z"
}

{
  "_id": "2",
  "user_id": "123-88",
  "department_id": "1",
  "type": "stop",
  "time": "2017-04-20T19:47:15.329Z"
}

What I want to do is find each unique user_id of department 1, only take the record with the latest time and tell me if they are oncall or not. So in the example above user 123-88 is not oncall now. How would you make this query? I know you will need something like this:

TimeCard.aggregate([
    { $match: {department_id: req.query.department_id}},
    { $sort: { user_id: 1, time: 1 }},
    { $group: { _id: "$user_id", lastTime: { $last: "$time" }}
    ], function(err, docs){
        if(err){console.log(err);}
        else {res.json(docs);}
    });

But I keep erroring so I know I am not correct in my logic. I know if I just have the match it works and if I add the sort it matches and sorts but the final group is not working. Thanks again for your help.



via Justin Yanta

No comments:

Post a Comment