MongoDB 聚合查询与 Node.js 中的 where

问题描述 投票:0回答:3

我在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());
    });
});

如何修改此查询以返回一个特定的邮政编码? 我已经尝试过条件子句,但未能使其发挥作用。

node.js mongodb
3个回答
2
投票

需要过滤结果的聚合可以使用

$match
运算符来完成。在不调整已有内容的情况下,我建议只需在聚合列表顶部返回您想要返回的邮政编码中添加
$match

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

此示例将导致

$match
之后的每个聚合操作仅工作于由 $match
 键的 
zip
 返回到值 
47421
 的数据集。


0
投票
在 $match 管道运算符中添加

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

作为旁注,您应该将 $match 运算符放在第一位,并且通常尽可能放在聚合链的较高位置。


0
投票
如果您尝试对对象 id 执行此操作但没有得到任何结果,请尝试使用 mongoose.Types.ObjectId(id)

例如:

{ $match: { userID: { $eq: new mongoose.Types.ObjectId(id) }, searchIndex: { $ne: -1 }, }, },
    
© www.soinside.com 2019 - 2024. All rights reserved.