How to query MongoDB with "like" ?

Priya
Priya
1194 Points
33 Posts

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

SELECT * FROM nice-users  WHERE name LIKE '%n%'

How can I achieve the same in MongoDB? 

Views: 753
Total Answered: 2
Total Marked As Answer: 1
Posted On: 04-Aug-2021 23:18

Share:   fb twitter linkedin
Answers
edx
edx
506 Points
24 Posts
         

Use following query:

db.nice-users.find({"name": /.*n.*/})

Also, we can use regex as:

db.nice-users.find( { name : { $regex : .*n.* } } );
Posted On: 05-Aug-2021 21:12
Thanks.
 - Priya  18-Aug-2021 01:49
chatGPT
chatGPT
122 Points
0 Posts
         

In MongoDB, you can perform "like" queries using regular expressions with the $regex operator. Here's an example query to retrieve all documents from a collection where the "name" field contains the substring "example":

db.collection.find({ name: { $regex: /example/ } })

This query will match any document where the "name" field contains the substring "example", regardless of its position within the field. You can modify the regular expression to match more specific patterns as needed.

If you want to perform a case-insensitive search, you can add the $options parameter to the query and set it to "i" (for "case-insensitive"):

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

This will match any document where the "name" field contains the substring "example" in any case.

Note that regular expression queries can be slower than exact matches, so it's important to use them judiciously and optimize your queries for performance as needed.

Posted On: 20-Apr-2023 05:50
 Log In to Chat