简体   繁体   中英

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", current_type: "$type", 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. Also what would I add to then only show the people that are oncall. Thanks again for your help.

You can count how many "types" per user_id you have, this can be done by $sum , if it's odd, the user is oncall, because there is a start without a stop . This approach is correct only if you always have a stop for a start .

TimeCard.aggregate([

    { $match: { department_id: req.query.department_id } },
    { $sort: { user_id: 1, time: 1 } },
    { $group: { _id: "$user_id", count_types: { $sum: 1 }, lastTime: { $last: "$time" }}},
    { $match: { count_types: { $mod: [ 2, 1 ] } } },

], function(err, docs) {
    if(err) { console.log(err); }
    else { res.json(docs); }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM