我已经使用SQL Server很长一段时间,只是真正学习MongoDB。我想弄清楚如何做聚合发现以获得我想要的数据。下面是从数据库中的样本:Node.js调用MongoDB的聚合查找
{
"_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"
}
我想要做的就是找到部门1的每个唯一USER_ID什么,只需要使用最新的时间记录,并告诉我,如果他们是OnCall中与否。所以在上面的例子中,用户123-88现在没有通话。你如何做这个查询?我知道你会需要这样的东西:
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);}
});
但我一直错误,所以我知道我在我的逻辑不正确。我知道如果我只是匹配它的作品,并且如果我添加它匹配和排序的排序,但最终的组不起作用。此外,我会添加什么,然后只显示oncall的人。再次感谢你的帮助。
它不工作,因为'current_type'必须是累加器。如果你想在'current_type'中拥有每一个'type',你可以使用[$ push](https://docs.mongodb.com/manual/reference/operator/aggregation/push/#grp._S_push)。 – luisenrike
谢谢luisenrike。我想我不明白。我虽然该组只会让我回到每个不同user_id的所有user_id,type和lasttime。这是不正确的? –
是的,没错。 – luisenrike