$out operator in MongoDB

$out is responsible for writing a specific collection taking documents returned by aggregation pipeline. We should keep $out at the last stage in the pipeline. $out operator gives the facility to return a result set of any size.


{ $out: "<output-collection>" }

When you use a $out operator it creates a new collection in the current database. It is just like a view in SQL Server but it creates such a table. If you want to aggregate some documents from the collection and want to write in a new collection then you have to use a $out operator in MongoDB. $out operator creates a new collection if aggregation succeeds if aggregation failed It will not create a collection.

$out operation replace the existing collection if already exists in the current database, mean if you are performing aggregation using $out operation and collection already exists in a database which is specified by $out, it replaces the existing collection with $out specify collection. If operation filed then no changes made in the database. If the previous collection has any index it will not change when replacing with new.

If there are not any unique field in $out collection then the operation will be failed, you have to use _id including index in the output collection.









The above collection (EMP) created for employees and the projects. Suppose we have to create a new collection where to summarize employee’s projects.
 Run the following query.

db.EMP.aggregate( [

               { $group : { _id : "$Name", Projects: { $push: "$Project" } } },

               { $out : "EmpProject" }

            ] ) 

It will create a new collection in the current database. New the collection will create with the name “EmpProject” look like below.

 { "_id" : "Pankaj", "Projects" : [ "Pro7" ] }

 { "_id" : "Vipul", "Projects" : [ "Pro3", "Pro4", "Pro5" ] }

 { "_id" : "Dilip", "Projects" : [ "Pro1", "Pro2", "Pro6" ] }

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

NUnit : Introduction

There are several unit test tools in the market, but one of them is NUnit, the most popular tool for doing unit testing. So in this tutorial...