Skip to content Skip to sidebar Skip to footer

In MongoDB, How To Perform Query Based On If One String Field Contains Another

Hello please help me with this. In mongodb, I have a collection like this: data1= { 'string1':'abc', 'string2':'abcde' } data2= { 'string1':'abc', 'string2':'ftgr'

Solution 1:

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

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

Or more directly by also using $redact:

db.test.aggregate([
    {$redact: {
        $cond: {
            if: { $eq: [{$indexOfCP: ['$string2', '$string1']}, -1]},
            then: '$$PRUNE',
            else: '$$KEEP'
        }
    }}
])

Post a Comment for "In MongoDB, How To Perform Query Based On If One String Field Contains Another"