在MongoDB中返回具有不同字段和1select查询的整个文档

我有困难编写一个查询,返回整个文档,同时仍然有1个不同的领域。 我已经试图混乱总结,但无济于事。 googlesearch了一段时间之后我已经find了这个文件:

如何有效地执行多个键“独特”?

它描述了我需要的大部分解决scheme,但是我还需要在另一个领域进行筛选。

这是我现在用来查询TempCollection中文档的sorting列表的function。

function getLatestUserData(UserID, callback) { console.log("in func " + UserID); Temp.find({ UId: UserID }).sort({ "created_at" : -1 }).exec( function (err, data) { console.log(data + " " + err); callback(data); }); }; 

然而,我无法弄清楚如何在同一时间过滤,分类和清除所有的东西。

这是使用Aggregates的一个尝试,然而,阅读文章已经有相当长的一段时间了,我只是无法弄清楚我需要的语法:

 function getLatestUserData(UserID, callback) { Temp.aggregate([ {"$group": { "_id": { value: "$value", SerialNumber: "$SerialNumber" } }}, {$filter : {input: "$UId", as: "UId", cond: {$U: [ "$UId", UserID ]} }} ]).exec( function (err, data) { callback(data); }); }; 

这是TempCollection的一部分:

 /* 1 */ { "updatedAt" : ISODate("2017-05-23T13:01:45.000Z"), "created_at" : ISODate("2017-05-23T13:01:45.000Z"), "UId" : "590b10221da091b2618a4913", "value" : 36, "SerialNumber" : "TEST2", "_id" : ObjectId("592432b9372464833d038b80"), "__v" : 0 } /* 2 */ { "updatedAt" : ISODate("2017-05-23T14:23:39.000Z"), "created_at" : ISODate("2017-05-23T14:23:39.000Z"), "UId" : "58f8954c3602b80552b6f1fb", "value" : 39, "SerialNumber" : "IIOJOIMJ", "_id" : ObjectId("592445eb372464833d038bf4"), "__v" : 0 } 

任何帮助深表感谢!

您需要在UID上添加$match ,而不是$filter (仅用于数组字段),然后在desc $sort上对distinct_keys和$group进行$sort ,同时在$first累积运算符中使用$$ROOTvariables来select最新整个文档。

就像是

  Temp.aggregate([ {"$match":{ "UId": UserID }}, {"$sort":{ "created_at" : -1 }}, {"$group": { "_id": { value: "$value", SerialNumber: "$SerialNumber" }, "data":{"$first":"$$ROOT"}}} ]) 

data字段将有最新的文档。