简体   繁体   English

mongodb聚合过滤器并依靠nodejs

[英]mongodb aggregate filter and count on nodejs

I have this collection named "points" 我有一个名为“ points”的收藏集

[
    { 'guid': 'aaa' },
    { 'guid': 'bbb' },
    { 'guid': 'ccc' },
]

and I have another named "stream" 而且我还有一个名为“流”的

[
    { 'title': 'pippo', 'guid': 'aaa', 'email': 'pippo@disney'},
    { 'title': 'pluto', 'guid': 'aaa', 'email': 'pluto@disney'},
    { 'title': 'goofy', 'guid': 'bbb', 'email': 'goofy@disney'},
    { 'title': 'duck', 'guid': 'aaa', 'email': 'duck@disney'},
    { 'title': 'minnie', 'guid': 'ccc', 'email': 'minnie@disney'},
]

I need to do an aggregate query where I want to search email that contains letter "o". 我需要在汇总查询中搜索包含字母“ o”的email The results that I expect is this 我期望的结果是这样

[
    { 'guid': 'aaa', items: 2 },
    { 'guid': 'bbb', item: 1 },
    { 'guid': 'ccc', item: 0 },
]

I have already done this 我已经做过了

db.getCollection('points').aggregate([
    {
        $lookup: {
            from: "stream",
            localField: "guid",
            foreignField: "guid",
            as: "items"
        }
    },
    {
        $project: {
            _id: 0,
            guid: 1,
            items: {
                $size: "$items"
            }
        }
    }
]);

If I were in mysql the query will be this 如果我在mysql中,查询将是这样

SELECT DISTINCT 
    points.guid, 
    (
        SELECT COUNT(*) 
        FROM stream 
        WHERE guid = stream.guid and stream.email like '%o%'
    ) AS items 
FROM points

Answer is edited based on comment. 根据评论编辑答案。

You can try the following aggregation pipeline. 您可以尝试以下聚合管道。

db.getCollection("points").aggregate([
                        {"$lookup":{"from":"stream", "localField":"guid", "foreignField":"guid", as:"items"}},
                        {"$unwind":"$items"}, 
                        {"$group":{"_id": "$guid", "guid":{"$first":"$guid"}, "emails":{"$push":"$items.email"}}},
                        {"$project":{"guid" :1, "emails":{"$setUnion":["$emails", [{"$literal":"io"}]]}}}, 
                        {"$unwind":"$emails"}, 
                        {"$match":{"emails":/[io]/}}, 
                        {"$group":{"_id":"$guid", "items":{"$sum":1}}}, 
                        {"$project":{"_id":0, "guid":"$_id", "items":{"$add":["$items", -1]}}}
                    ])

Sample Output: 样本输出:

{ "items" : 3, "guid" : "aaa" }
{ "items" : 1, "guid" : "ccc" }
{ "items" : 1, "guid" : "bbb" }

Note: I have introduced a dummy email id - 'oi', that satisfies matching condition, to ensure that data from point collection are not lost. 注意:我引入了一个虚拟电子邮件ID-'oi',该ID满足匹配条件,以确保来自点收集的数据不会丢失。 And to compensate this dummy field -1 is subtracted finally from the count. 为了补偿该虚拟字段-1,最后从计数中减去-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM