How to find a substring in a field in Mongodb

Instead of this:

db.database.find({A: {$regex: '/^*(abc def)*$/''}})

You should do this:

db.database.find({A: /abc def/i })

^* is not actually valid syntax as ^ and $ are anchors and not something that is repeatable. You probably meant ^.* here. But there is no need for ^.* as that simply means "Everything up to the character following" and (abc def)* means "0 or more times "abc def", but it has to be at the end of the string, because of your $. The "i" at the end is to make it case insensitive.


$regex is too expensive/slow on large collections.

I'd suggest to leverage aggregation framework and $indexOfCP.

db.test.aggregate([{$match: 
    {$expr: { $gt: [{ $indexOfCP: [ "$A", "Star Wars" ] }, -1]}}
    }, {$project: {A:1}}])

For case-insensitive search you may add $toUpper to the mix and search for STAR WARS.


Just use the string "Star Wars" and $regex will do the rest

db.test.find({A: {$regex: 'Star Wars'}})

This worked for me:

db.test.find({"A": {'$regex': '.*star wars.*'}})

Tags:

Nosql

Mongodb