MongoDB使用node.js中的where来聚合查询

我在node.js中有以下的mongodb查询,它给了我一个唯一的邮政编码列表,其中包含邮政编码出现在数据库中的次数。

collection.aggregate( [ { $group: { _id: "$Location.Zip", count: { $sum: 1 } } }, { $sort: { _id: 1 } }, { $match: { count: { $gt: 1 } } } ], function ( lookupErr, lookupData ) { if (lookupErr) { res.send(lookupErr); return; } res.send(lookupData.sort()); }); }); 

如何修改这个查询来返回一个特定的邮政编码? 我已经试过条件条款,但一直没有能够得到它的工作。

需要过滤结果的聚合可以使用$match操作符完成。 在不调整你已经有的东西的情况下,我build议你只需要在汇总列表的顶部附加一个你想要返回的邮政编码即可。

 collection.aggregate( [ { $match: { zip: 47421 } }, { $group: { ... 

这个例子将导致$match之后的每个聚合操作处理由zip密钥的$match返回到值47421的数据集。

在$ matchpipe道运算符中添加

 { $match: { count: { $gt: 1 }, _id : "10002" //replace 10002 with the zip code you want }} 

作为一个方面说明,你应该把$ match运算符放在聚合链中,并且一般来说可以。