In this tutorial you will learn about the Node.js MongoDB Filter Query and its application with practical example.
Node.js MongoDB Filter Query
While finding records in a MongoDB collection, you can pass search parameters using query object to filter the MongoDb result. The query object is used to limit the search result.
Example :- Let’s select records from “employees” collection where emp_name is “Keith”.
Step 1:- Let’s, create a node_mongo_filter.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 |
var http = require('http'); var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/nodemongo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var query = { emp_name: "Keith" }; db.collection("employees").find(query).toArray(function(err, res) { if (err) throw err; console.log(res); db.close(); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mongo_filter.js |
you will see following output on terminal –
Output:-
An error has occurred. Please try again later. |
Node.js MongoDB Filter With Regular Expression
Example :- Let’s select records from “employees” collection where emp_name starts with the letter “S”.
Step 1:- Let’s, create a node_mongo_filter_regex.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 |
var http = require('http'); var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/nodemongo"; MongoClient.connect(url, function(err, db) { if (err) throw err; var query = { emp_name: /^S/ }; db.collection("employees").find(query).toArray(function(err, res) { if (err) throw err; console.log(res); db.close(); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mongo_filter_regex.js |
you will see following output on terminal –
Output:-
1 2 3 4 |
[ { _id: 58fdbf5c0ef8a50b4cdd9a87 , emp_name: "Steve", emp_age: "28", emp_salary: "7500"}, { _id: 58fdbf5c0ef8a50b4cdd9a88 , emp_name: "Scott", emp_age: "40", emp_salary: "10000"} ] |