Home » MongoDB

Use of $gte with find in MongoDB

In this article we are going learn about $gte and the method to use of instead of $gt in MongoDB.
Submitted by Manu Jemini, on March 24, 2018

In below example, first we need to start our MongoDB server and then, we will follow further process as given below.

$gte in MongoDB means greater than equal to, to find a document in MongoDB through an Express server we need to full fill certain requirements:

Read more in previous article: How to use $gt in MongoDB?

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: "ferrari", qty:{ $gte: 1} }).
    toArray(function(err,res){ })

Now, this function will search every document with the matching field of company name as “nisaan” and quantity greater than equal to 1.

Console the error if any and then we will go for the connection that needs to be get closed by simply calling a method of db which is close();

JS file 1)

// 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 $gte
		collection.find({company_name: "nissan", qty:{ $gte: 127} }).toArray(function(err,res){
			if(err)
			{
				console.log(err);
			}
			else if(res.length)
			{
				console.log(res);
			}
			else
			{
				console.log('No car found');
			}
			db.close();
		})
	}
});

JS file 2)

// 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 $gte
		collection.find({company_name: "nissan", qty:{ $gte: 932} }).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:

Use of $gte with find in MongoDB 1

Output in shell:

Use of $gte with find in MongoDB 2



Comments and Discussions!

Load comments ↻





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