How to find a substring in a field in Mongodb

MongodbNosql

Mongodb Problem Overview


How can I find all the objects in a database with where a field of a object contains a substring?

If the field is A in an object of a collection with a string value:

I want to find all the objects in the db "database" where A contains a substring say "abc def".

I tried:

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

but didn't work

UPDATE

A real string (in unicode):

Sujet  Commentaire sur  Star Wars  Episode III - La Revanche des Sith 1

Need to search for all entries with Star Wars

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

Mongodb Solutions


Solution 1 - 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.

Solution 2 - Mongodb

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

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

Solution 3 - Mongodb

$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.

Solution 4 - Mongodb

This worked for me:

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

Solution 5 - Mongodb

// executes, name LIKE john and only selecting the "name" and "friends" fields
db.collection.find({ name: /john/i }, 'name friends').exec();

// passing options
db.collection.find({ name: /john/i }, null, { skip: 10 }).exec();

Solution 6 - Mongodb

this one uses the aggregation syntax:

db.movies.aggregate([
  {$match: 
    {
      title: {$regex: 'Star'}
    } 
  }
] )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodiousView Question on Stackoverflow
Solution 1 - MongodbDerickView Answer on Stackoverflow
Solution 2 - MongodbLuisCarlos RodriguezView Answer on Stackoverflow
Solution 3 - Mongodbdev101View Answer on Stackoverflow
Solution 4 - MongodbAlex JoligView Answer on Stackoverflow
Solution 5 - Mongodbkartik tyagiView Answer on Stackoverflow
Solution 6 - MongodbDrorView Answer on Stackoverflow