【问题标题】:In MongoDB, how to perform query based on if one string field contains another在MongoDB中,如何根据一个字符串字段是否包含另一个来执行查询
【发布时间】:2017-04-20 11:17:16
【问题描述】:

您好,请帮帮我。 在 mongodb 中,我有一个这样的集合:

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

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

查询后我只想返回 data1 因为它的 string2 属性包含它的 string1 属性的内容。我怎样才能使这项工作?我应该使用 $where 还是使用正则表达式?如果有人可以指点小费,非常感谢。

【问题讨论】:

  • 我有点不清楚您是希望查询执行此操作,还是要在查询完成后过滤结果。
  • 另外,这里似乎已经使用 $where 或聚合回答了这个问题:codeschool.com/discuss/t/…

标签: javascript mongodb


【解决方案1】:

您可以使用 $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'
        }
    }}
])

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2013-03-13
    • 2014-07-24
    • 2020-07-19
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多