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

标签 javascript mongodb

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

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

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

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

最佳答案

您可以使用 $where 执行此操作,方法是为 string1 创建一个 RegExp,然后针对 string2 进行测试:

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

但是,如果您使用的是 MongoDB 3.4+,则可以使用 $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'
        }
    }}
])

关于javascript - 在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40984829/

相关文章:

javascript - 过滤和组合具有相同属性的对象数组中的索引

javascript - Node.js:在模块范围内使用时, `this` 运算符的上下文是什么?

Javascript:基于选择 1 禁用选择 2 中的选择选项

javascript - 在 jQuery 中启动 .hover 后,如何检查鼠标是否仍在悬停?

javascript - (Javascript) 如何使用 iframe 强制下载图像?

node.js - 我应该在 Node.js 中同时使用 MongoDB 和 Mongoose 吗?

mongodb - ElasticSearch索引和对其他文档的引用

java - 使用 Java 连接到 Azure 中的 MongoDB

mongodb - Grails MongoDB无法保存在afterUpdate中

node.js - Mean.IO 的 NPM 安装在更新 Bower 依赖项时卡住