Mauro Sala
Mauro Sala

Reputation: 1186

mongodb aggregate filter and count on nodejs

I have this collection named "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". 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

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

Upvotes: 2

Views: 2213

Answers (1)

4J41
4J41

Reputation: 5095

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. And to compensate this dummy field -1 is subtracted finally from the count.

Upvotes: 1

Related Questions