在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询 [英] In MongoDB, how to perform query based on if one string field contains another

查看:2904
本文介绍了在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello please help me with this. In mongodb, I have a collection like this:

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

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

查询后,我只想返回data1,因为它的string2属性包含其string1属性的内容.我该如何进行这项工作?我应该使用$ where还是使用正则表达式?如果有人可以给小费,我将非常感激.

After the query I only want to return data1 because it's string2 property contains the contents of it's string1 property. How can I make this work? Should I use $where or using regex? Very very appreciated if someone can point a tip.

推荐答案

您可以通过为string1创建一个RegExp然后针对string2对其进行测试,来对$where进行此操作:

You can do this with $where by creating a RegExp for string1 and then testing it against string2:

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

但是,如果您使用的是MongoDB 3.4+,则可以使用

However, if you're using MongoDB 3.4+ you can do this more efficiently by using the $indexOfCP aggregation operator:

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'
        }
    }}
])

这篇关于在MongoDB中,如何根据一个字符串字段是否包含另一个字符串字段来执行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆