【问题标题】:GROUP BY tags in tags array inside foreign collection外部集合内标签数组中的 GROUP BY 标签
【发布时间】:2019-06-10 19:45:25
【问题描述】:

我正在寻找按位于 collection2 上的标签对 collection1 进行分组 这两个集合需要通过 2 个字段 (field1, field2) 连接(查找)

到目前为止,我想出了以下查询:

db.collection1.aggregate([
{
        "$lookup": {
            "from": "collection2",
            "let": { _field1: '$field1', _field2: '$field2' },
            "pipeline": [{
                "$match": {
                    "$expr": {
                        "$and": [
                            { "$eq": ["$field1", "$$_field1"] },
                            { "$eq": ["$field2", "$$_field2"] }
                        ]
                    }
                }
            },
            { "$project": { _id: 0, tags: 1 } },
            ],
            "as": "col2"
        }
    },
    { "$unwind": "$col2" },
    { $group: { _id: "$col2.tags", count: { $sum: 1 } } }

    ]);

我没有得到任何结果。

field1 和 field2 在 collection2 中是唯一的(具有唯一索引)

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    除了变量名之外,您的语法是正确的:

    { _field1: '$field1', _field2: '$field2' },

    当您定义此类变量时,它们被称为user variables,mongo 对它们有一定的命名限制,这与“真实”变量约定不同。

    来自文档:

    用户变量名称必须以小写 ascii 字母 [a-z] 或非 ascii 字符开头。

    在您的情况下意味着下划线导致错误。

    【讨论】:

    • 10x mate,但是将用户变量更改为 uv_field1 和 uv_field2 没有任何区别
    • 在我的本地它可以正常工作,并且在更改之前它会引发错误,我认为是时候检查字段名称和架构字段类型以确保找到匹配项。我所说的语法是正确的。
    【解决方案2】:

    好的,我自己解决了。

    1. 我在 collection2 (filed1,field2) 上添加了唯一索引
    2. 添加了额外的展开以展平标签数组

    我的最后一个查询是傻瓜:

     db.collection1.aggregate([
    {
            "$lookup": {
                "from": "collection2",
                "let": { field1: '$field1', field2: '$field2' },
                "pipeline": [{
                    "$match": {
                        "$expr": {
                            "$and": [
                                { "$eq": ["$field1", "$$field1"] },
                                { "$eq": ["$field2", "$$field2"] }
                            ]
                        }
                    }
                },
                { "$project": { _id: 0, tags: 1 } },
                ],
                "as": "col2"
            }
        },
        { "$unwind": "$col2" },
        { "$unwind": "$col2.tags" },
        { $group: { _id: "$col2.tags", count: { $sum: 1 } } }
    { $sort: { count: -1 } },
        ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      相关资源
      最近更新 更多