NodeJS MongoDB Query

Query in MongoDB is different from a relational database like MySQL. In MongoDB, a query cannot perform operations on a database like creating collections, inserting documents, deleting documents, etc.

A query is used to filter the result return when selecting the documents from a collection. A query object which contains the query inside a JavaScript object is passed as an argument to the methods find() and findOne() to filter the selection.

For example, suppose we have to select the document of that student whose age is equal to “18”. If we use the find() method without query it will select all of them but if we pass a query object { age: “18” } then the method find() only return those documents when the age field is exactly equal to “18”.

We have already covered the find() and findOne() methods in a separate tutorial NodeJS MongoDB Select if you want to read.

Filter the Selection Using NodeJS MongoDB Query

A query object is passed as a first argument to find() and findOne() method to filter the result.

Syntax:

database.collection(collectionName).findOne(query, function(err, document) {
    if (err) throw err;
    console.log(document);
});

where,

  • database is a database object,
  • collectionName is the name of a collection
  • query is a query object

Example

We have multiple documents in a collection.

Documents

If you want to learn to insert multiple records in a collection then read our previous tutorial NodeJS MongoDB Insert Record.

Below is an example of a query to filter the selection.

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db("newdatabase");

  const query = { name: "Rack" };
  database.collection("newcollection").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
  });
});

Here the query object { name: “Rack” } is filtering the selection and returns only those documents where the name field is equal to “Rack”.

Run the Code:

To run the above code, create a project folder, and copy and paste the above code into a JavaScript file.

Then locate the folder in the terminal and execute the below command to install the MongoDB module.

npm install mongodb

Then execute the below command to run the code.

node fileName

where fileName is the name of the JavaScript file where you have inserted the code.

Output:

Query To Filter Documents

The collection has multiple documents, so the find() method selects all of them but the query filters them to only get the one where the name field is equal to “Rack”.

Using Regular Expression to Filter Selections in NodeJS Query

Regular Expression can be used to filter the selection on the basis of some symbols, characters, or groups of characters.

Example:

Below is an example of filtering the selection using a regular expression to select all the documents where the name starts with the letter “R”.

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

MongoClient.connect("mongodb://localhost:27017/", function (err, client) {
  if (err) throw err;
  const database = client.db("newdatabase");

  const query = { name: /^R/  };
  database.collection("newcollection").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
  });
});

Run the Code:

To run the above code, create a project folder, and copy and paste the above code into a JavaScript file.

Then locate the folder in the terminal and execute the below command to install the MongoDB module.

npm install mongodb

Then execute the below command to run the code.

node fileName

where fileName is the name of the JavaScript file where you have inserted the code.

Output:

Regular Expressions Output

Here we only get those documents where the name field starts with the letter “R”.

Summary

Query in MongoDB is used to filter the selected documents. A query is passed inside a JavaScript object after which it is called a query object. This query object is passed as an argument to the method find() and findOne() to find the documents from a collection and then filter them according to the condition of the query. Hope this tutorial helps you to understand the concept of MongoDB queries and how to use them in NodeJS to filter the selection.

Reference

https://www.mongodb.com/docs/realm/sdk/node/examples/query-mongodb/

Aditya Gupta
Aditya Gupta
Articles: 109