在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询

2024-01-01

你好,请帮我解决这个问题。 在 mongodb 中,我有一个这样的集合:

data1= {
    "string1":"abc",
    "string2":"abcde"
}

data2= {
    "string1":"abc",
    "string2":"ftgr"
}

查询后我只想返回 data1 因为它是string2属性包含其内容string1财产。我怎样才能做到这一点?我应该使用 $where 还是使用正则表达式?如果有人能指点迷津,非常非常感激。


你可以这样做$where通过创建一个RegExp for string1然后对其进行测试string2:

db.test.find({$where: 'RegExp(this.string1).test(this.string2)'})

但是,如果您使用的是 MongoDB 3.4+,您可以使用以下命令更有效地完成此操作:$indexOfCP https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfCP/#exp._S_indexOfCP聚合运算符:

db.test.aggregate([
    // Project  the index of where string1 appears in string2, along with the original doc.
    {$project: {foundIndex: {$indexOfCP: ['$string2', '$string1']}, doc: '$$ROOT'}},
    // Filter out the docs where the string wasn't found
    {$match: {foundIndex: {$ne: -1}}},
    // Promote the original doc back to the root
    {$replaceRoot: {newRoot: '$doc'}}
])

或者更直接地使用$redact:

db.test.aggregate([
    {$redact: {
        $cond: {
            if: { $eq: [{$indexOfCP: ['$string2', '$string1']}, -1]},
            then: '$$PRUNE',
            else: '$$KEEP'
        }
    }}
])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询 的相关文章

随机推荐