Gobi
Gobi

Reputation: 303

How to use "value%" with like keyword in MongoDB

I can execute below query in MongoDB

MySQL:

SELECT * FROM users WHERE user_id like "bc%;

MongoDB:

db.users.find( { user_id: /^bc/ } )

The above query is working. But below query is not working anyone please me give suggestion.

MySQL:

SELECT * FROM users WHERE user_id like "%bc";

MongoDB:

db.users.find( { user_id: /bc^/ } );

Upvotes: 0

Views: 146

Answers (2)

Nicolas Heimann
Nicolas Heimann

Reputation: 2581

In Regex the ^ character labels the start of the subject. Putting it on the right hand side is therefore not meaningful.

Instead, the "end of the string" analogue to ^ is $:

db.users.find( { user_id: /bc$/ } );

This translates to: Find users where the last two characters of the user_id attribute are 'bc'.

Upvotes: 2

Dharmesh Hadiyal
Dharmesh Hadiyal

Reputation: 729

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 regexp's '.*'), not something that has "m" anchored to the beginning of the string.

Please check for more Info: How to query MongoDB with "like"?

Upvotes: 1

Related Questions