Home » MongoDB

Find documents of a collection in MongoDB?

In this article, we are going to learn about the method to find documents of a collection in MongoDB database.
Submitted by Manu Jemini, on February 02, 2018

Now we are working on MongoDB, the most famous no sql database for fast data transmission and data reliability.

So, in this article we need to find an existing collection in MongoDB and then print the result (output) on console.

To find a collection in document 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";
  4. After fulfill the above three conditions, we should make connection to the database like this: MongoClient.connect(url, function(err,db){})
  5. 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');
  6. Now in the example below we have to drop this collection by using the function drop: collection.find().toArray(function(err,res){ })

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, if the length of the array is more than 0, we will log the result of the query, otherwise we will log that no match found.

To make an optimum server to work smooth we should always close the connection after our use of it. There the last thing we do is close the db.

db.close();

JS code:

// 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 documents
		collection.find().toArray(function(err,res){
		if(err)
		{
		console.log(err);
		}else if(res.length)
		{
		console.log(res);
		}else
		{
		// if no cars found
		console.log('No cars found');
		}
		db.close();
		})
	}

});

Output on console

MongoDB - find documents of a collection 1

Output in shell

MongoDB - find documents of a collection 2

MongoDB - find documents of a collection 3

MongoDB - find documents of a collection 4



Comments and Discussions!

Load comments ↻





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