$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.

Syntax:


{ $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.

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"}


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.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...