Home »
MongoDB
Single purpose aggregation-pipeline in MongoDB
In this article, we are going to learn about single purpose aggregation pipeline and the method to use it in MongoDB.
Submitted by Manu Jemini, on March 08, 2018
Single purpose pipeline stages provide filters that operate like queries and document transformations that modify the form of the output document. A record is a mongo document that is composed of field and value pairs. The documents are like JSON objects. Just like JSON in mongo 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?
In the example below we have to count for the documents.
collection.count(function(err,res){ })
Now this function will count every document.
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 by using close() method.
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 documents
collection.count(function(err,res){
if(err)
{
console.log(err);
}else
{
//to console the response.
console.log(res);
}
db.close();
})
}
});
Server Running:
Output in console:
Output in shell: