Home » MongoDB

How to use $eq in MongoDB?

In this article, we are going to learn about the method to use $eq in MongoDB for finding suitable data.
Submitted by Manu Jemini, on February 10, 2018

Here, we find a document in MongoDB through an Express server we need to full fill certain requirements:

  1. You must have MongoDB install: npm install MongoDB
  2. You must import, mogodb in the express server: var MongoDB = require('MongoDB')
  3. You should always specify the URL for MongoDB in accordance with your system: var url = "MongoDB://localhost:27017/vehicle";

After fulfill the above three conditions, we should make connection to the database like this:

MongoClient.connect(url, function(err,db){})

Then we have to make sure if there is any error or not with an if-else statement. If there is no error open a collection with its name.

var collection = db.collection('cars');

Now in the example below, we have to search for the matching company name and quantity in this collection by using the function find,

collection.find({company_name: "nissan", qty:{ $eq: 200} }).
toArray(function(err,res){ });

Now, this function will search every document with the matching field of company name as nisaan and quantity 200.

Just like before we have to check for the error, if any. So to check if there is any error we use simple if-else statements.

The Object error will be passed by mongo itself and it will be false or null if there is no error, otherwise we will get an error object.

If we found an error we will console.log it, otherwise we will log the result of the query.

There the last thing we do is close the db.

db.close();

JS file

// require MongoDB
var MongoDB = require('MongoDB');
var MongoClient = MongoDB.MongoClient;
//create url
var url = "MongoDB://localhost:27017/vehicle";
//connect with mongo client
MongoClient.connect(url, function(err,db){

	if(err)
	{
		console.log(err);
	}
	else
	{
		//console.log tthe connected url
		console.log('Connected to ',url);

		//get refernce of using collection
		var collection = db.collection('cars');

		// to find the document using $eq
		collection.find({company_name: "nissan", qty:{ $eq: 200} }).toArray(function(err,res){
			if(err)
			{
				console.log(err);
			}else if(res.length)
			{
				console.log(res);
			}else
			{
				console.log('No car found');
			}
			db.close();
		})
	}
});

Output in console and shell (when satisfy the condition):

Use of $eq 1
Use of $eq 2

Output in console and shell (when not satisfy the condition):

Use of $eq 3


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.