我在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
运算符来完成。在不调整已有内容的情况下,我建议只需在聚合列表顶部返回您想要返回的邮政编码中添加 $match
。
collection.aggregate( [
{
$match: {
zip: 47421
}
},
{
$group: {
...
此示例将导致
$match
之后的每个聚合操作仅工作于由 $match
键的
zip
返回到值
47421
的数据集。
{ $match: { count: { $gt: 1 },
_id : "10002" //replace 10002 with the zip code you want
}}
作为旁注,您应该将 $match 运算符放在第一位,并且通常尽可能放在聚合链的较高位置。
例如:
{
$match: {
userID: { $eq: new mongoose.Types.ObjectId(id) },
searchIndex: { $ne: -1 },
},
},