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){

		//console.log tthe connected url
		console.log('Connected to ',url);

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

		// to find the documents

		{$sort: {qty:1}},
		{$group: {_id:"$id",total_quantity: { $push: "$qty" }}}],function(err,res){
				//to console the response.

Output in console:

Aggregation pipeline to create a new format of document in MongoDB 1

Output in shell:

Aggregation pipeline to create a new format of document in MongoDB 2

Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com (2015-2018), Some rights reserved.