mongodb聚合过滤器和nodejs的计数

时间:2016-09-26 12:47:48

标签: javascript node.js mongodb aggregation-framework mongodb-aggregation

我有这个名为“points”的集合

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

我有另一个名为“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'},
]

我需要进行汇总查询,我想搜索包含字母“o”的email。我期待的结果就是这个

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

我已经完成了这个

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

如果我在mysql中,查询将是这个

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

1 个答案:

答案 0 :(得分:0)

根据评论编辑答案。

您可以尝试以下聚合管道。

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]}}}
                    ])

示例输出:

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

注意:我已经引入了一个虚拟电子邮件ID - ' oi',它满足匹配条件,以确保来自点集合的数据不会丢失。为了补偿这个虚拟场,最后从计数中减去-1。