Node.js MongoDB Query

Here is a clean, simple, and complete guide for Node.js MongoDB Query — also known as MongoDB Find with Conditions.


Node.js MongoDB Query (Find With Conditions)

To “query” in MongoDB means using find() or findOne() with filters.

MongoDB filters allow you to select documents using:

  • Field matching

  • Comparison operators

  • Logical operators

  • Pattern matching (regex)

  • Array queries

  • Nested document queries

Below are all important query examples using Node.js.


1. Basic Query (LIKE WHERE)

Find documents where name = "John"

const result = await collection.findOne({ name: "John" });

Find all matching

const results = await collection.find({ name: "John" }).toArray();

2. Query With Multiple Conditions (AND)

Equivalent to SQL: WHERE name='John' AND address='Highway 37'

const results = await collection.find({
name: "John",
address: "Highway 37"
}).toArray();

3. OR Query

SQL Equivalent: WHERE name='John' OR name='Peter'

const results = await collection.find({
$or: [
{ name: "John" },
{ name: "Peter" }
]
}).toArray();

4. Comparison Operators

OperatorMeaning
$gtGreater than
$ltLess than
$gteGreater or equal
$lteLess or equal
$neNot equal
$inMatch any in array
$ninNot in array

Example: age > 25

const results = await collection.find({ age: { $gt: 25 } }).toArray();

Example: Age between 20 and 30

const results = await collection.find({
age: { $gte: 20, $lte: 30 }
}).toArray();

5. Query Using Regular Expression (LIKE in SQL)

Find names starting with “J”

const results = await collection.find({
name: /^J/
}).toArray();

Contains “hn”

const results = await collection.find({
name: /hn/
}).toArray();

6. Query Nested Documents

If your document is like:

{
name: "John",
address: { city: "Vapi", pincode: 396195 }
}

Query nested field:

const results = await collection.find({
"address.city": "Vapi"
}).toArray();

7. Query Arrays

Find where “tags” array contains “nodejs”

const results = await collection.find({
tags: "nodejs"
}).toArray();

Using $in

const results = await collection.find({
tags: { $in: ["nodejs", "mongodb"] }
}).toArray();

8. Logical Operators

$and

collection.find({
$and: [
{ age: { $gt: 25 } },
{ city: "Surat" }
]
});

$not

collection.find({
age: { $not: { $gt: 30 } }
});

9. Query With Sort & Limit

const results = await collection
.find({ city: "Surat" })
.sort({ age: -1 }) // -1 DESC, 1 ASC
.limit(5)
.toArray();

Full Example Program

const { MongoClient } = require("mongodb");

const url = “mongodb://localhost:27017/”;
const client = new MongoClient(url);

async function run() {
try {
await client.connect();

const db = client.db(“mydb”);
const collection = db.collection(“customers”);

const results = await collection.find({
age: { $gte: 25 },
city: “Surat”
}).toArray();

console.log(results);
} finally {
await client.close();
}
}

run();

You may also like...