bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Node.js/Database Integration
Node.js•Database Integration

Node.js 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

Find documents with the address "Park Lane 38":

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:

Run "demo_mongodb_query.js"

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.

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

Find documents where the address starts with the letter "S":

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:

Run "demo_mongodb_query_s.js"

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' }
]

Previous

Node.js MongoDB Find

Next

Node.js MongoDB Sort

This chapter

Overview
24

Lessons

70m

Read time

1. Node.js MySQL2. Node.js MySQL Create Database3. Node.js MySQL Create Table4. Node.js MySQL Insert Into5. Node.js MySQL Select From6. Node.js MySQL Where7. Node.js MySQL Order By8. Node.js MySQL Delete9. Node.js MySQL Drop Table10. Node.js MySQL Update11. Node.js MySQL Limit12. Node.js MySQL Join13. Node.js MongoDB14. Node.js MongoDB Create Database15. Node.js MongoDB Create Collection16. Node.js MongoDB Insert17. Node.js MongoDB Find18. Node.js MongoDB Query19. Node.js MongoDB Sort20. Node.js MongoDB Delete21. Node.js MongoDB Drop22. Node.js MongoDB Update23. Node.js MongoDB Limit24. Node.js MongoDB Join

On this page

Filter the ResultFilter With Regular Expressions