具有两个字段的Mongo聚合匹配

时间:2020-04-18 08:44:17

标签: mongodb

我进行了有效的汇总,其中在字段和计算值之间进行了匹配。但是后来我意识到我需要按两个计算值进行搜索,所以我引入了两个新字段。我需要将两者的匹配项汇总在一起,但是无法构造mongo查询。它要么什么都不匹配,要么什么都不匹配。我被尝试了很多可能性而陷入困境。你能找到我做错了什么吗?

数据模型:

db.items.find({"info.slug": "otaceni-na-dalnici"});
{ "_id" : "1e44kgsl1s", "info" : { "slug" : "otaceni-na-dalnici"}, "votes_count" : 9 }

db.poll_votes.find({poll: "1e44kgsl1s", user: "1e41795qjw"});
{ "_id" : "1e44kgsl1s_1e41795qjw", "poll" : "1e44kgsl1s", "user": "1e41795qjw", "vote" : "dislike"}

原始查询:

db.items.aggregate([{$match: {"info.slug": "otaceni-na-dalnici"}},
{$lookup: {
    from: 'poll_votes',
    let: {poll_id: "$_id"},
    pipeline: [{$match: {$expr: {$eq: ["$_id", {$concat: ["$$poll_id", "_1e41795qjw"]}]}}}, 
    {$project: {_id: 0, vote: "$vote"}}],
    as: "me"
}}]).pretty();

及其简化的响应:

{
    "_id" : "1e44kgsl1s",
    "info" : {
            "slug" : "otaceni-na-dalnici",
    },
    "votes_count" : 9,
    "me" : [{"vote" : "dislike"}]
}

使用polluser字段的新查询。

db.items.aggregate([{$match: {"info.slug": "otaceni-na-dalnici"}},
{$lookup: {
        from: 'poll_votes', 
        let: {poll_id: "$_id"},
        pipeline: [{$match: {$expr: {$and: [{poll: "$$poll_id"}, {user: "1e41795qjw"}]}}},
        {$project: {_id: 0, vote: "$vote"}}], as: "me"
    }
}]);

但是尽管有$and运算符,但它会为所有用户返回poll_votes

 {
 "_id": "1e44kgsl1s",
 "info": {"slug": "otaceni-na-dalnici"},
 "votes_count": 9,
 "me": [{"vote": "dislike"}, {"vote": "neutral"}, {"vote": "neutral"}, {"vote": "neutral"}, {"vote": "hate"}, {"vote": "neutral"}, {"vote": "trivial"}]

}

怎么了?我尝试设置mongo沙箱,但无法识别我的聚合查询。这是测试数据

db={
    "items": [
        {
            "_id": "1e44kgsl1s",
            "info": {
                "slug": "otaceni-na-dalnici"
            },
            "votes_count": 9
        }
    ],
    "poll_votes": [
        {
            "_id": "1e44kgsl1s_1e41795qjw",
            "poll": "1e44kgsl1s",
            "user": "1e41795qjw",
            "vote": "dislike"
        },
        {
            "_id": "xyz",
            "poll": "1e44kgsl1s",
            "user": "abc",
            "vote": "dislike"
        },
        {
            "_id": "ijk",
            "poll": "1e44kgsl1s",
            "user": "qwerty",
            "vote": "dislike"
        },

    ]
}

1 个答案:

答案 0 :(得分:1)

您正在$expr中混用普通的mongo查询语言和聚合运算符。

需要该变量的谓词应位于$expr内,而普通谓词则不应:

db.items.aggregate([
    {$match: {"info.slug": "otaceni-na-dalnici"}},
    {$lookup: {
        from: 'poll_votes', 
        let: {poll_id: "$_id"},
        pipeline: [
        {$match: {$and: [
                    {$expr: {$eq:["$poll", "$$poll_id"]}}, 
                    {user: "1e41795qjw"}
        ]}}
    }},
    {$project: {_id: 0, vote: "$vote"}}], as: "me"}
}]);

Playground