【问题标题】:Query for documents where match contiguous array elements查询匹配连续数组元素的文档
【发布时间】:2021-03-18 18:26:46
【问题描述】:

我有一个 MongoDB 集合,其中包含以下格式的文档:

    { "_id" : 1, "tokens": [ "I", "have", "a", "dream" ] },
    { "_id" : 2, "tokens": [ "dream", "a", "little", "dream" ] },
    { "_id" : 3, "tokens": [ "dream", "a", "dream" ] },
    { "_id" : 4, "tokens": [ "a" , "little", "dream" ] },
    ...

我需要获取所有“令牌”包含连续数组元素的文件:“a”、“dream”。 因此,以下是匹配的文件:

    { "_id" : 1, "tokens": [ "I", "have", "a", "dream" ] },
    { "_id" : 3, "tokens": [ "dream", "a", "dream" ] },

有没有办法得到正确的结果?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    使用正则表达式的技巧。

    • $match 获取所有具有$all 数组输入的文档
    • $addFields 复制令牌和输入数组
    • $reduce 有助于连接所有加入 - 的字符串
    • $regexMatch 匹配两个字符串
    • $match 消除不需要的数据
    • $project 仅获取必要的字段

    代码是

    [{
        $match: {
            tokens: { $all: ["a", "dream"] }
        }
    }, {
        $addFields: {
            duplicate: "$tokens",
            inputData: ["a", "dream"]
        }
    }, {
        $addFields: {
            duplicate: {
                $reduce: {
                    input: "$duplicate",
                    initialValue: "",
                    in: { $concat: ["$$value", "-", "$$this"] }
                }
            },
            inputData: {
                $reduce: {
                    input: "$inputData",
                    initialValue: "",
                    in: { $concat: ["$$value", "-", "$$this"] }
                }
            }
        }
    }, {
        $addFields: {
            match: {
                $regexMatch: { input: "$duplicate", regex: '$inputData' }
            }
        }
    }, {
        $match: {
            match: true
        }
    }, {
        $project: {  _id: 1,  tokens: 1 }
    }]
    

    工作Mongo playground

    注意:请检查多个场景,尽管它适用于这种场景

    【讨论】:

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