X.Xin
X.Xin

Reputation: 27

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"
}

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.

Upvotes: 2

Views: 119

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311945

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

Upvotes: 2

Related Questions