1890

I want to query something with SQL's like query:

SELECT * FROM users  WHERE name LIKE '%m%'

How can I achieve the same in MongoDB? I can't find an operator for like in the documentation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 11
    see mongodb's docs: Advanced Queries -- Regular expressions http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions – douyw Nov 22 '11 at 13:21
  • 2
    I seriously suggest taking a look at MongoDB Atlas Search, as it is much more resource efficient and feature rich for "like"-like queries that `$text` or `$regex` – Nice-Guy Mar 18 '22 at 19:31

46 Answers46

2485

That would have to be:

db.users.find({"name": /.*m.*/})

Or, similar:

db.users.find({"name": /m/})

You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to regular expressions' '.*'), not something that has "m" anchored to the beginning of the string.

Note: MongoDB uses regular expressions which are more powerful than "LIKE" in SQL. With regular expressions you can create any pattern that you imagine.

For more information on regular expressions, refer to Regular expressions (MDN).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kyle H
  • 24,914
  • 1
  • 15
  • 3
  • 136
    is searching by regex expensive? – Freewind Jul 22 '10 at 10:13
  • 171
    Actually, it depends. If the query doesn't use an index, and must do a table scan, then it can certainly be expensive. If you're doing a 'starts with' regex query, then that can use an index. Best to run an explain() to see what's happening. – Kyle Banker Jul 22 '10 at 14:49
  • 41
    When not anchored to the beginning of the string, it is somewhat expensive. But then again, so is a `LIKE` query in SQL. – Emily Jul 26 '10 at 18:50
  • 59
    I would add regex i ```javascript db.users.find({ "name": { $regex: /m/i } }) ``` – Doron Segal Jun 19 '15 at 03:24
  • 7
    It is worth mentioning that if you want to use it from Node app and you want a dynamic search, you can use: `users.find({"name": new RegExp('.*' + searchVariable + '.*')})` So, this way you can use it with other operators like $in, $nin, etc. – Ivan Cabrera Jul 30 '21 at 21:18
  • @Ivan Cabrera, yes it is worth noting, as is putting '.*' anywhere there is whitespace. Othrer DBMS's allow perppered %. – mckenzm Aug 23 '21 at 02:27
  • 1
    Why ".*" at the beginning and end of the regex seems "optional" in you example? Does Mongo treat the regex /somePattern/ automatically as "contains somePattern"? – Marcus Castanho Dec 15 '21 at 20:54
  • showing syntax error for /m/ while using pymongo. what is correct syntax in python? – Sundar Mar 14 '22 at 04:03
  • Just make sure that you escape the values that you place in this regex correctly especially if this is something that a user can input values into. You can cause Mongo to throw exceptions if its not properly escaped. – KSigWyatt Oct 06 '22 at 04:10
  • Please not that these is no quotations in /m/ – shamaseen Jul 11 '23 at 12:47
622
db.users.insert({name: 'patrick'})
db.users.insert({name: 'petra'})
db.users.insert({name: 'pedro'})

Therefore:

For:

db.users.find({name: /a/})  // Like '%a%'

Output: patrick, petra

For:

db.users.find({name: /^pa/}) // Like 'pa%'

Output: patrick

For:

db.users.find({name: /ro$/}) // Like '%ro'

Output: pedro

Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
Johnathan Douglas
  • 8,807
  • 2
  • 14
  • 7
380

In

  • PyMongo using Python
  • Mongoose using Node.js
  • Jongo, using Java
  • mgo, using Go

you can do:

db.users.find({'name': {'$regex': 'sometext'}})
Kirill Husiatyn
  • 828
  • 2
  • 12
  • 20
Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201
  • 93
    @TahirYasin if you're still wondering, case-insensitive search would be done like this: `db.users.find({'name': {'$regex': 'sometext', '$options': 'i'}})` – sumowrestler Jul 14 '17 at 00:09
  • 1
    this applies to the whole word, not to a part of the word. – Revol89 Oct 03 '21 at 17:01
107

In PHP, you could use the following code:

$collection->find(array('name'=> array('$regex' => 'm'));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Leon
  • 2,810
  • 5
  • 21
  • 32
  • You can also specify the flags in the second item of the $regex array, like so: `$collection->find(array('name'=> array('$regex' => 'm', '$options => 'i'));` – Diego Lope Loyola Oct 13 '22 at 15:16
104

Here are different types of requirements and solutions for string search with regular expressions.

You can do with a regular expression which contains a word, i.e., like. Also you can use $options => i for a case insensitive search.

Contains string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

Doesn't contain string, only with a regular expression

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

Exact case insensitive string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

Start with string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

End with string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

Keep Regular Expressions Cheat Sheet as a bookmark, and a reference for any other alterations you may need.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
  • this is a later comment but, how can I use a variable in above example? like let name = 'john doe' . how can I implement name variable in regex? thanks – Irfan Habib Aug 26 '21 at 15:29
72

You would use a regular expression for that in MongoDB.

For example,

db.users.find({"name": /^m/})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joshua Partogi
  • 16,167
  • 14
  • 53
  • 75
56

You have two choices:

db.users.find({"name": /string/})

or

db.users.find({"name": {"$regex": "string", "$options": "i"}})

For the second one, you have more options, like "i" in options to find using case insensitive.

And about the "string", you can use like ".string." (%string%), or "string.*" (string%) and ".*string) (%string) for example. You can use a regular expression as you want.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alvescleiton
  • 1,063
  • 11
  • 8
46

If using Node.js, it says that you can write this:

db.collection.find( { field: /acme.*corp/i } );

// Or
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

Also, you can write this:

db.collection.find( { field: new RegExp('acme.*corp', 'i') } );
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eddy
  • 3,623
  • 37
  • 44
31

Already you got the answers, but to match with a regular expression with case insensitivity, you could use the following query:

db.users.find ({ "name" : /m/i } ).pretty()

The i in the /m/i indicates case insensitivity and .pretty() provides a prettier output.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The6thSense
  • 8,103
  • 8
  • 31
  • 65
24

For Mongoose in Node.js:

db.users.find({'name': {'$regex': '.*sometext.*'}})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aqib Mumtaz
  • 4,936
  • 1
  • 36
  • 33
18

With MongoDB Compass, you need to use the strict mode syntax, as such:

{ "text": { "$regex": "^Foo.*", "$options": "i" } }

(In MongoDB Compass, it's important that you use " instead of ')

damd
  • 6,116
  • 7
  • 48
  • 77
  • 1
    This nearly drove me crazy much appreciated, and why can't they give documentation or examples on doing things like this for Compass. I couldn't even find documentation on the strict mode syntax for Compass. – zerodoc Jan 03 '23 at 15:01
18

In MongoDb, can use like using MongoDb reference operator regular expression(regex).

For Same Ex.

MySQL - SELECT * FROM users  WHERE name LIKE '%m%'

MongoDb

    1) db.users.find({ "name": { "$regex": "m", "$options": "i" } })

    2) db.users.find({ "name": { $regex: new RegExp("m", 'i') } })

    3) db.users.find({ "name": { $regex:/m/i } })

    4) db.users.find({ "name": /mail/ })

    5) db.users.find({ "name": /.*m.*/ })

MySQL - SELECT * FROM users  WHERE name LIKE 'm%'

MongoDb Any of Above with /^String/

    6) db.users.find({ "name": /^m/ })

MySQL - SELECT * FROM users  WHERE name LIKE '%m'

MongoDb Any of Above with /String$/

    7) db.users.find({ "name": /m$/ })
Sahil Thummar
  • 1,926
  • 16
  • 16
16

You can use the new feature of MongoDB 2.6:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cmarrero01
  • 691
  • 7
  • 21
  • 8
    Note, AFAIK Mongodb's text searching works on whole words only by default, so this will match values like "This is a string with text", but not "This is a string with subtext". So it's not quite like sql's "LIKE" operator. – rocketmonkeys Mar 10 '15 at 18:34
15

In a Node.js project and using Mongoose, use a like query:

var User = mongoose.model('User');

var searchQuery = {};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
User.find(searchQuery, function(error, user) {
                if(error || user === null) {
                    return res.status(500).send(error);
                }
                return res.status(200).send(user);
            });
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
14

You can use a where statement to build any JavaScript script:

db.myCollection.find( { $where: "this.name.toLowerCase().indexOf('m') >= 0" } );

Reference: $where

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
briba
  • 2,857
  • 2
  • 31
  • 59
13

String yourdb={deepakparmar, dipak, parmar}

db.getCollection('yourdb').find({"name":/^dee/})

ans deepakparmar

db.getCollection('yourdb').find({"name":/d/})

ans deepakparmar, dipak

db.getCollection('yourdb').find({"name":/mar$/})

ans deepakparmar, parmar

12

In Go and the mgo driver:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

where the result is the struct instance of the sought-after type.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
12

In SQL, the ‘like’ query looks like this:

select * from users where name like '%m%'

In the MongoDB console, it looks like this:

db.users.find({"name": /m/})     // Not JSON formatted

db.users.find({"name": /m/}).pretty()  // JSON formatted

In addition, the pretty() method will produce a formatted JSON structure in all the places which is more readable.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MADHAIYAN M
  • 2,028
  • 25
  • 22
12

For PHP mongo Like.

I had several issues with PHP mongo like. I found that concatenating the regular expression parameters helps in some situations - PHP mongo find field starts with.

For example,

db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);

// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)

// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);

output: (joe, john, jason)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dap
  • 2,309
  • 5
  • 32
  • 44
11

Using template literals with variables also works:

{"firstname": {$regex : `^${req.body.firstname}.*` , $options: 'si' }}

besthost
  • 759
  • 9
  • 14
10

Regular expressions are expensive to process.

Another way is to create an index of text and then search it using $search.

Create a text index of fields you want to make searchable:

db.collection.createIndex({name: 'text', otherField: 'text'});

Search for a string in the text index:

db.collection.find({
  '$text'=>{'$search': "The string"}
})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
8

Use regular expressions matching as below. The 'i' shows case insensitivity.

var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", new BsonRegularExpression("ABCD", "i")), 
         Query.Matches("strVal", new BsonRegularExpression("4121", "i")));

var queryB = Query.Or(
       Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
       Query.Matches("strVal", new BsonRegularExpression("33156", "i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);
Abhijit Bashetti
  • 8,518
  • 7
  • 35
  • 47
Shalabh Raizada
  • 354
  • 2
  • 8
7

It seems that there are reasons for using both the JavaScript /regex_pattern/ pattern as well as the MongoDB {'$regex': 'regex_pattern'} pattern. See: MongoDB RegEx Syntax Restrictions

This is not a complete regular expression tutorial, but I was inspired to run these tests after seeing a highly voted ambiguous post above.

> ['abbbb','bbabb','bbbba'].forEach(function(v){db.test_collection.insert({val: v})})

> db.test_collection.find({val: /a/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.*a.*/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.+a.+/})
{ "val" : "bbabb" }

> db.test_collection.find({val: /^a/})
{ "val" : "abbbb" }

> db.test_collection.find({val: /a$/})
{ "val" : "bbbba" }

> db.test_collection.find({val: {'$regex': 'a$'}})
{ "val" : "bbbba" }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149
6

A like query would be as shown below:

db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);

For the Scala ReactiveMongo API,

val query = BSONDocument("title" -> BSONRegex(".*" + name + ".*", "")) // like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prayagupa
  • 30,204
  • 14
  • 155
  • 192
5

If you are using Spring-Data MongoDB, you can do it in this way:

String tagName = "m";
Query query = new Query();
query.limit(10);
query.addCriteria(Criteria.where("tagName").regex(tagName));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vaibhav
  • 2,073
  • 4
  • 23
  • 26
5

If you have a string variable, you must convert it to a regex, so MongoDB will use a like statement on it.

const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });

Is the same result as:

db.users.find({"name": /John/})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

One way to find the result as with equivalent to a like query:

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

Where i is used for a case-insensitive fetch data.

Another way by which we can also get the result:

db.collection.find({"name":/aus/})

The above will provide the result which has the aus in the name containing aus.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
waseem khan
  • 305
  • 5
  • 10
4

If you want a 'like' search in MongoDB then you should go with $regex. By using it, the query will be:

db.product.find({name:{$regex:/m/i}})

For more, you can read the documentation as well - $regex

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jarry jafery
  • 1,018
  • 1
  • 14
  • 25
4

Use aggregation substring search (with index!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);
kz_sergey
  • 677
  • 5
  • 19
4

You can query with a regular expression:

db.users.find({"name": /m/});

If the string is coming from the user, maybe you want to escape the string before using it. This will prevent literal chars from the user to be interpreted as regex tokens.

For example, searching the string "A." will also match "AB" if not escaped. You can use a simple replace to escape your string before using it. I made it a function for reusing:

function textLike(str) {
  var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  return new RegExp(escaped, 'i');
}

So now, the string becomes a case-insensitive pattern matching also the literal dot. Example:

>  textLike('A.');
<  /A\./i

Now we are ready to generate the regular expression on the go:

db.users.find({ "name": textLike("m") });
Ezequias Dinella
  • 1,278
  • 9
  • 12
4

Use:

const indexSearch = await UserModel.find(
      { $text: { $search: filter } },
    );

    if (indexSearch.length) {
      return indexSearch;
    }
    return UserModel.find(
      {
        $or: [
          { firstName: { $regex: `^${filter}`, $options: 'i' } },
          { lastName: { $regex: `^${filter}`, $options: 'i' } },
          { middleName: { $regex: `^${filter}`, $options: 'i' } },
          { email: { $regex: `^${filter}`, $options: 'i' } },
        ],
      },
    );

I used a combination of regex and "index".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shubham Kakkar
  • 581
  • 6
  • 4
3

As the MongoDB shell supports regular expressions, that's completely possible.

db.users.findOne({"name" : /.*sometext.*/});

If we want the query to be case-insensitive, we can use the "i" option, like shown below:

db.users.findOne({"name" : /.*sometext.*/i});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sravanthi
  • 247
  • 1
  • 6
3

MongoRegex has been deprecated.

Use MongoDB\BSON\Regex:

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Albert S
  • 2,552
  • 1
  • 22
  • 28
3

Use:

db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

When we are searching for string patterns, it is always better to use the above pattern as when we are not sure about case.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
priya raj
  • 362
  • 2
  • 8
3

There are various ways to accomplish this.

The simplest one:

db.users.find({"name": /m/})

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

db.users.find({ "name": { $regex: "m"} })

More details can be found in $regex.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ajay_full_stack
  • 494
  • 7
  • 13
3

Using a JavaScript RegExp

  • split the name string by space and make an array of words
  • map to an iterate loop and convert the string to a regex of each word of the name

let name = "My Name".split(" ").map(n => new RegExp(n));
console.log(name);

Result:

[/My/, /Name/]

There are two scenarios to match a string,

  1. $in: (it is similar to the $or condition)

Try $in Expressions. To include a regular expression in an $in query expression, you can only use JavaScript regular expression objects (i.e., /pattern/). For example:

db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]
  1. $all: (it is similar to a $and condition) a document should contain all words
db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]

Using nested $and and $or conditionals and $regex

There are two scenarios to match a string,

  1. $or: (it is similar to the $in condition)
db.users.find({
  $or: [
    { name: { $regex: "My" } },
    { name: { $regex: "Name" } }
    // if you have multiple fields for search then repeat same block
  ]
})

Playground

  1. $and: (it is similar to the $all condition) a document should contain all words
db.users.find({
  $and: [
    {
      $and: [
        { name: { $regex: "My" } },
        { name: { $regex: "Name" } }
      ]
    }
    // if you have multiple fields for search then repeat same block
  ]
})

Playground

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
turivishal
  • 34,368
  • 7
  • 36
  • 59
3

If you want to use mongo JPA like query you should try this.

@Query("{ 'title' : { $regex: '^?0', $options: 'i' } }")
List<TestDocument> findLikeTitle(String title);
Sahil Patel
  • 534
  • 1
  • 6
2

I found a free tool to translate MySQL queries to MongoDB: http://www.querymongo.com/

I checked with several queries. As I see it, almost all of them are correct. According to that, the answer is

db.users.find({
    "name": "%m%"
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lakmal Vithanage
  • 2,767
  • 7
  • 42
  • 58
2

For the Go driver:

filter := bson.M{
    "field_name": primitive.Regex{
        Pattern: keyword,
        Options: "",
    },
}
cursor, err := GetCollection().Find(ctx, filter)

Use a regex in the $in query (MongoDB documentation: $in):

filter := bson.M{
    "field_name": bson.M{
        "$in": []primitive.Regex{
            {
                Pattern: keyword,
                Options: "",
            },
        }
    }
}
cursor, err := GetCollection().Find(ctx, filter)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
g10guang
  • 4,647
  • 3
  • 28
  • 22
1

If you're using PHP, you can use the MongoDB_DataObject wrapper like below:

$model = new MongoDB_DataObject();

$model->query("select * from users where name like '%m%'");

while($model->fetch()) {
    var_dump($model);
}

Or:

$model = new MongoDB_DataObject('users);

$model->whereAdd("name like '%m%'");

$model->find();

while($model->fetch()) {
    var_dump($model);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CEDA
  • 55
  • 4
1

FullName like 'last' with status==’Pending’ between two dates:

db.orders.find({
      createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
      $lt:ISODate("2017-05-05T10:08:16.111Z")},
      status:"Pending",
      fullName:/last/}).pretty();

status== 'Pending' and orderId LIKE ‘PHA876174’:

db.orders.find({
     status:"Pending",
     orderId:/PHA876174/
     }).pretty();
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
0
>> db.car.distinct('name')
[ "honda", "tat", "tata", "tata3" ]

>> db.car.find({"name":/. *ta.* /})
B--rian
  • 5,578
  • 10
  • 38
  • 89
Vishe
  • 3,383
  • 1
  • 24
  • 23
0

You can also use the wildcard filter as follows:

{"query": { "wildcard": {"lookup_field":"search_string*"}}}

Be sure to use *.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
saim2025
  • 280
  • 2
  • 5
  • 14
0

Here is the command which uses the "starts with" paradigm:

db.customer.find({"customer_name" : { $regex : /^startswith/ }})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KayV
  • 12,987
  • 11
  • 98
  • 148
0

Just in case, someone is looking for an SQL LIKE kind of query for a key that holds an array of strings instead of a string, here it is:

db.users.find({"name": {$in: [/.*m.*/]}})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Binita Bharati
  • 5,239
  • 1
  • 43
  • 24
0

The previous answers are perfectly answering the questions about the core MongoDB query. But when using a pattern-based search query such as:

{"keywords":{ "$regex": "^toron.*"}}

or

{"keywords":{ "$regex": "^toron"}}

in a Spring Boot JPA repository query with @Query annotation, use a query something like:

@Query(value = "{ keyword : { $regex : ?0 }  }")
List<SomeResponse> findByKeywordContainingRegex(String keyword);

And the call should be either of:

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron");

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron.*");

But never use:

List<SomeResponse> someResponseList = someRepository.findByKeywordsContainingRegex("/^toron/");

List<SomeResponse> someResponseList =someRepository.findByKeywordsContainingRegex("/^toron.*/");

An important point to note: each time the ?0 field in @Query statement is replaced with a double quoted string. So forwardslash (/) should not be used in these cases! Always go for a pattern using double quotes in the searching pattern!! For example, use "^toron" or "^toron.*" over /^toron/ or /^toron.*/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Priyanka Wagh
  • 615
  • 1
  • 8
  • 17