Skip to main content

Node.js MongoDB Queries

nodejs mongodb query


Queries


We will learn how to to find the data from the database in this tutorial. To find documents in a collection we can filter the results using the query object. This query object is passed as the first argument of the find() method. We can limit the search with the help of this query object. 

If you have not learned about how to create a collection in MongoDB with Node.js and place the documents in that collection with node JS, then read the previous tutorial

This tutorial includes

  • The find() method
  • Query Object
  • AND query
  • OR query
  • Conditional queries
  • Regular Expression Query
  • Special Query Options
  • Querying inside Objects and Arrays
  • Query Options
  • Paging
  • Sorting

The find() method

The syntax of the find() method on Collection is,

collection.find(query[[[, fields], options], callback]); 
  • The “query” is an object representing query and specifying the conditions the documents need to be passed.
  • The “fields” represent the fields that should be contained by the response (by default all fields are included)
  • The “options” provide extra logic such as sorting options, paging, etc.
  • The “raw” driver is used to supply documents as BSON binary Buffer objects (by default value is false)
  • The “callback” has two arguments. The first argument an error object (if case some error occurs). The second argument is a cursor object.

To select entire data from a collection we can use {} as a query object.

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

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({}) .toArray(function(error, result) {
    //Query object is left {}
    if (error) throw error;
    console.log("===========Selected Documents===========");
    console.log(result);
    database.close();
  });
});

Output:
===========Selected Documents===========
[
  {
    _id: 5ea81ce29e5f1044ec12710b,
    name: 'Jhony',
    dept: 'HR',
    salary: '10000'
  },
  {
    _id: 5ea8223ffb74b00a3889b2f5,
    name: 'Shiva',
    dept: 'Sales',
    salary: '15000'
  },
  {
    _id: 5ea8223ffb74b00a3889b2f6,
    name: 'Alex',
    dept: 'Sales',
    salary: '12500'
  },
  {
    _id: 5ea8223ffb74b00a3889b2f7,
    name: 'Viraj',
    dept: 'Marketing',
    salary: '20000'
  }
]

The Query Object


We can make selection limited by applying an appropriate query object. For example, if we want to find a document with a given name, then we can pass {name:'any_name'} as a query object.

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

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({name:'Shiva'}) .toArray(function(error, result) {
    //Query object is set {name:'Shiva'}
    if (error) throw error;
    console.log("===========Selected Document===========");
    console.log(result);
    database.close();
  });
});

Output:
===========Selected Document===========
[
  {
    _id: 5ea8223ffb74b00a3889b2f5,
    name: 'Shiva',
    dept: 'Sales',
    salary: '15000'
  }
]

AND Query

If more than one field is specified than it is a AND query.

For example,

{ 
key1: "val1", 
key2: "val2" 
}

This query will return all records where key1 is “val1” and key2 is “val2”.

OR Query

OR queries can be performed with the $or operator. Query operator consumes an array containing multiple query objects. At least one of these query objects must match a document to get any results.

{
  $or:[
    {name:"Shiva"},
    {dept:"HR"}
  ]
}

For example,

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

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({
  $or:[    //OR Query
    {name:"Shiva"},
    {dept:"HR"}
  ]
}
) .toArray(function(error, result) {
    if (error) throw error;
    console.log("===========Selected Documents===========");
    console.log(result);
    database.close();
  });
});

Output:
===========Selected Document===========
[
  {
    _id: 5ea81ce29e5f1044ec12710b,
    name: 'Jhony',
    dept: 'HR',
    salary: '10000'
  },
  {
    _id: 5ea8223ffb74b00a3889b2f5,
    name: 'Shiva',
    dept: 'Sales',
    salary: '15000'
  }
]

Conditional Query

The Query object does not support operators like <, <=, >, >= and !=. However, this can be achieved with their aliases $lt, $lte, $gt, $gteand $ne. To match the values with conditional, the value needs to be wrapped in a separate object. 

{"salary":{$gte:10000}}
OR
{"salary":{$gte:10000,$lte:15000}}

We can also mix them to create ranges.

For example,

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

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({"salary":{$gte:"12500",$lte:"15000"}}) .toArray(function(error, result) {
    if (error) throw error;
    console.log("===========Selected Documents===========");
    console.log(result);
    database.close();
  });
});

Output:
===========Selected Documents===========
[
  {
    _id: 5ea8223ffb74b00a3889b2f5,
    name: 'Shiva',
    dept: 'Sales',
    salary: '15000'
  },
  {
    _id: 5ea8223ffb74b00a3889b2f6,
    name: 'Alex',
    dept: 'Sales',
    salary: '12500'
  }
]

Regular Expression query

We can also use a regular expression to filter the results. For example, if we want to find the documents with the name field starting with "S".

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

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({name: /^S/}) .toArray(function(error, result) {
    //Query object is set {name: /^S/} //RegExp
    if (error) throw error;
    console.log("===========Selected Document===========");
    console.log(result);
    database.close();
  });
});

Output:
===========Selected Document===========
[
  {
    _id: 5ea8223ffb74b00a3889b2f5,
    name: 'Shiva',
    dept: 'Sales',
    salary: '15000'
  }
]

Special query operators 


There are few other operators like OR and conditionals to perform some special operations.
  • The ‘$in’ defines an array of possible matches, {" field_name ":{$in:[1,2,3]}}
  • The ‘$nin’ defines an array of not required matches
  • The ‘$all’ is used to check that array value must match to the condition {" field_name ":{$all:[1,2,3]}}
  • The ‘$exists’ is used to check if a given field exists or not {"field_name":{$exists:true}}
  • The ‘$mod’ is used to check for a modulo {" field_name ":{$mod:{7,3}} is equivalent to " field_name " % 7 == 3
  • The ‘$size’ is used to check the size of an array value {" field_name ": {$size:5}} matches arrays name with 5 elements

Querying inside the Objects and Arrays


If the documents are nested then they can be easily retrieved by the (.) operator. For example, we have an object such as,

{
  "_id": id,
  "name":{
    "firstname":"Shiva",
    "lastname": "Kumar"
  },
  "address":[
    {
      "city":"Delhi",
      "street": "1/714",
      "state": "Delhi"
    }
  ]
}

We can write the query objects like,

collection.find({"name.firstname":"Shiva"})
OR
collection.find({"address.city":"delhi"})

Query options


Query options specify the appearance and the behavior of the query execution.

For example,

var query_options = {
    "limit": 20,
    "skip": 10,
    "sort": "title"
}

collection.find({}, query_options).toArray(...); 

Paging


Paging is applied by 'limit' and 'skip' options.

{
  "limit": 20,
  "skip": 10
}

can be applied to find 10 elements starting from 20.

Sorting


Sorting can be applied using the 'sort' parameter.

{
  "sort": [['field_name1','asc'], ['field_name2','desc']]
}

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...