Home »
MongoDB
Aggregation pipeline to create a new format of document in MongoDB
In this article, we are going to learn about the aggregation pipeline and its purpose to create a new format of document in MongoDB.
Submitted by Manu Jemini, on March 08, 2018
Aggregation 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 first group the document and then sort them for the documents.
collection.aggregate([{$sort: {qty:1}},
{$group: {_id:"$id",total_quantity:
{ $push: "$qty" }}}], function(err,res){ });
Now this function will return every document in a sorted group of descending _id which gave matching parameters.
As the result or we can say output of the query is come we just need to print it on console and that we are free to close our connection we made with mongo server and last important thing is, we need to console the error if any so that we can easily identify it and debug our code.
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.aggregate([
{$sort: {qty:1}},
{$group: {_id:"$id",total_quantity: { $push: "$qty" }}}],function(err,res){
if(err)
{
console.log(err);
}
else
{
//to console the response.
console.log(res);
}
db.close();
});
}
});
Output in console:
Output in shell: