How to query with like in mongodb?

Member

by ryleigh , in category: PHP Databases , 8 months ago

How to query with like in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 3 months ago

@ryleigh 

To query a MongoDB collection using the like operator, you can use the $regex operator. The $regex operator allows you to specify a regular expression that the query will match against.


Here is an example of how you can use the $regex operator to perform a query that matches documents where the name field contains the string "John":

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


You can also use the $options operator to specify options for the regular expression, such as case insensitivity:

1
db.collection.find( { name: { $regex: /John/i } } )


You can also use the $regex operator in combination with other query operators, such as $and and $or, to create more complex queries.


For example, you can use the $and operator to match documents where the name field contains the string "John" and the age field is greater than 30:

1
db.collection.find( { $and: [ { name: { $regex: /John/ } }, { age: { $gt: 30 } } ] } )


You can learn more about the $regex operator and other MongoDB query operators in the MongoDB documentation.