🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Node.js Notes
Topic #64

MongoDB Query


Filter the Result

When finding documents in a collection, you can filter the result by using a query object.

The first argument of the find() method is a query object, and is used to limit the search.

Example

let MongoClient = require('mongodb').MongoClient;
let url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

let dbo = db.db("mydb");
  let query = { address: "Park Lane 38" };
  dbo.collection("customers").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();

});
});

Save the code above in a file called "demo_mongodb_query.js" and run the file:

C:\Users\Your Name>node demo_mongodb_query.js

Which will give you this result:

[
  { _id: 58fdbf5c0ef8a50b4cdd9a8e
, name: 'Ben', address: 'Park Lane 38' }
]

Filter With Regular Expressions

You can write regular expressions to find exactly what you are searching for.

Note: Regular expressions can only be used to query strings.

To find only the documents where the "address" field starts with the letter "S", use the regular expression /^S/:

Example

let MongoClient = require('mongodb').MongoClient;
let url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

let dbo = db.db("mydb");
  let query = { address: /^S/ };
  dbo.collection("customers").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();

});
});

Save the code above in a file called "demo_mongodb_query_s.js" and run the file:

C:\Users\Your Name>node demo_mongodb_query_s.js

Which will give you this result:

[
  { _id:
58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard',
address: 'Sky st 331' },
  { _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway
1633' }
]

Want to go beyond the notes?

Join CodingNow 2.0's Node.js course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

MongoDB Query – FAQs

Quick answers about learning MongoDB Query in Node.js.

This free note from CodingNow 2.0 explains MongoDB Query in Node.js — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Node.js topic on CodingNow 2.0, including MongoDB Query, is 100% free with no signup required.
With focused practice, most students grasp MongoDB Query in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now