Home » MongoDB

Find with a match field in MongoDB

In this article, we are going to learn about the process to use find with a known or match field in MongoDB.
Submitted by Manu Jemini, on March 24, 2018

Map reduce is for data processing for large volumes of data into aggregated results. A record is a mongo document that is composed of field and value pairs. The documents are like JSON objects. Just like JSON in MongoDB, we can put more documents inside a document.

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?

After fulfill the above three conditions (mentioned in linked post), 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 will produce a search operation,

    collection.find({type: "suv"}).toArray(function(err,res){ })

Now this function will return every document which matches that type equals to SUV.

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.

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

To make an optimum server to work smooth we should always close the connection after our use of it.

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 the connected url
		console.log('Connected to ',url);

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

		// to find the documents

		collection.find({type: "suv"}).toArray(function(err,res){
			if(err)
			{
				console.log(err);
			}
			else if(res.length)
			{
				console.log(res);
			}
			else
			{
				// console when no result found.
				console.log('No suv found');
			}
			db.close();
		})
	}
});

Output in console:

Find with a match field in MongoDB 1

Output in shell:

Find with a match field in MongoDB 1




Comments and Discussions!

Load comments ↻






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