How to query MongoDB with "like"?

 

In MongoDB, you can perform a "like" query using regular expressions (regex) with the $regex operator. This allows you to search for documents where a specific field matches a pattern. Here's how to query MongoDB with "like" using an example:

Suppose you have a collection called products, and you want to find all products whose names contain the word "apple."

javascript
const MongoClient = require('mongodb').MongoClient; const uri = 'mongodb://localhost:27017'; // Replace with your MongoDB URI const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); client.connect(async err => { if (err) { console.error('Error connecting to MongoDB:', err); return; } const db = client.db('your_database_name'); // Replace with your database name const collection = db.collection('products'); // Replace with your collection name const searchKeyword = 'apple'; // Perform a "like" query using a regular expression const query = { name: { $regex: searchKeyword, $options: 'i' } }; const products = await collection.find(query).toArray(); console.log('Products matching the "like" query:'); console.log(products); client.close(); });

In this example:

  1. We import the MongoClient from the MongoDB Node.js driver.

  2. We define the MongoDB connection URI (uri) and create a MongoDB client.

  3. We connect to the MongoDB server.

  4. We specify the database name and collection name you want to query.

  5. We define the searchKeyword, which is the term you want to search for (in this case, "apple").

  6. We construct a query using the $regex operator within the name field. The $options: 'i' flag makes the regex case-insensitive.

  7. We use collection.find(query) to find documents that match the "like" query.

  8. We convert the results to an array and log them to the console.

Remember to replace 'mongodb://localhost:27017', 'your_database_name', and 'products' with your specific MongoDB connection URI, database name, and collection name. This example will find all products whose names contain the word "apple" regardless of case.

Comments