在MongoDB数组中发送,以获取MongoDB中不同的集合的结果

我有一个包含时间卡的MongoDB集合。 我有第二个包含位置的集合。 通常情况下,我会这样做,如果我正在寻找任何人在当时oncall(你必须注册每个login):

TimeCard.aggregate([ { $match: {agency_id: req.query.agency_id}}, { $sort: { user_id: 1, received_time: -1 }}, { $group: { _id: "$user_id", count_types: { $sum: 1 }, lastTime: { $last: "$received_time" }}}, { $match: { count_types: { $mod: [2, 1] }}}, { $lookup: { from: "locations", localField: "_id", foreignField: "user_id", as: "Test" }} ], function(err, docs){ if(err){console.log(err);} else {res.json(docs);} }); 

这会给我这个结果:

  [ { "_id": "123-88", "count_types": 5, "lastTime": "2017-04-20T01:30:18.713Z", "Test": [ { "_id": "58fa4021ffa99100116585e0", "user_id": "123-88", "agency_id": "44", "contract_region_id": "contract-region-id-007", "department_id": "department-id-42", "shift_id": "shift-id-45", "unit_id": "unit-id-88", "received_time": "2017-04-21T17:23:45.672Z", "location": "Science Lab", "__v": 0 }, { "_id": "58fed3efdac1bd00112a914b", "user_id": "123-88", "agency_id": "44", "contract_region_id": "contract-region-id-007", "department_id": "department-id-42", "shift_id": "shift-id-45", "unit_id": "unit-id-88", "received_time": "2017-04-25T04:43:27.501Z", "location": "Gym", "__v": 0 } ] } ] 

现在我可以让arrays中的多个用户拥有自己的位置数据。 我想要的只是他们在的最后一个位置(基于received_time在testing数组内)。 所以我最好的猜测是,我需要首先得到一个user_ids的列表,然后调用第二个集合,并传递数组来获得结果,但我不知道如何正确地做到这一点,或者如果这是最好的方法去做这个。 再次感谢你的帮助。

使用$filter操作符获取Test数组中唯一的元素,其中received_time键与聚合的lastTime字段匹配。 如果您的MongoDB服务器版本是3.4或更高版本,则可以在$addFieldspipe道步骤中应用此步骤:

 TimeCard.aggregate([ { $match: {agency_id: req.query.agency_id}}, { $sort: { user_id: 1, received_time: -1 }}, { $group: { _id: "$user_id", count_types: { $sum: 1 }, lastTime: { $last: "$received_time" }}}, { $match: { count_types: { $mod: [2, 1] }}}, { $lookup: { from: "locations", localField: "_id", foreignField: "user_id", as: "Test" }}, { $addFields: { Test: { $filter: { input: "$Test", as: "user", cond: { $eq: ["$lastTime", "$$user.received_time"] } } } } } ], function(err, docs){ if(err){console.log(err);} else {res.json(docs);} }); 

如果您的MongoDB服务器不支持$addFields那么请使用$projectpipe道:

 TimeCard.aggregate([ { $match: {agency_id: req.query.agency_id}}, { $sort: { user_id: 1, received_time: -1 }}, { $group: { _id: "$user_id", count_types: { $sum: 1 }, lastTime: { $last: "$received_time" }}}, { $match: { count_types: { $mod: [2, 1] }}}, { $lookup: { from: "locations", localField: "_id", foreignField: "user_id", as: "Test" }}, { $project: { count_types: 1, lastTime: 1, Test: { $filter: { input: "$Test", as: "user", cond: { $eq: ["$lastTime", "$$user.received_time"] } } } } } ], function(err, docs){ if(err){console.log(err);} else {res.json(docs);} });