In MongoDB, how to execute a query based on if one string field contains another

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

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

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

After the request, I only want to return data1, because the property string2contains the contents of this property string1. How can I do this job? Should I use $ where or use regex? Very very grateful if someone could point the tip.

+2
source share
1 answer

You can do this with $where, by creating RegExpfor string1, and then checking it with 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'
        }
    }}
])
+2

Source: https://habr.com/ru/post/1676482/


All Articles