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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape ge

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component