2

「ポイント」という名前のこのコレクションがあります

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

そして、「ストリーム」という別の名前があります

[
    { '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'},
]

email文字「o」を含む検索対象の集計クエリを実行する必要があります。私が期待する結果はこれです

[
    { '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
4

1 に答える 1

1

回答はコメントに基づいて編集されます。

次の集計パイプラインを試すことができます。

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 が差し引かれます。

于 2016-09-26T15:23:09.123 に答える