Jun 30, 2016

$out operator in MongoDB

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

Syntax:


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


When you use $out operator it create a new collection in current data base, It just like a view in SQL Server but it create as table. If you want to aggregate some document from collection and want to write in a new collection then you have to use $out operator in mongodb. $out operator create new collection if aggregation succeed if aggregation failed It will not create a collection.

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

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

Example:


{_id:1,Name:"Dilip",Project:"Pro1"}

{_id:2,Name:"Dilip",Project:"Pro2"}

{_id:3,Name:"Vipul",Project:"Pro3"}

{_id:4,Name:"Vipul",Project:"Pro4"}

{_id:5,Name:"Vipul",Project:"Pro5"}

{_id:6,Name:"Dilip",Project:"Pro6"}

{_id:7,Name:"Pankaj",Project:"Pro7"}


Above collection (EMP) created for employee 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 new collection in current database. New collection will create with name “EmpProject” look like below.


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

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

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