0

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^/ } );
Joundill
  • 6,828
  • 12
  • 36
  • 50
Gobi
  • 283
  • 1
  • 5
  • 15

2 Answers2

2

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

Nicolas Heimann
  • 2,561
  • 16
  • 27
1

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

Community
  • 1
  • 1
Dharmesh Hadiyal
  • 719
  • 1
  • 7
  • 18