On this page
$out (aggregation)
On this page
New in version 2.6.
Definition
$out
-
Takes the documents returned by the aggregation pipeline and writes them to a specified collection. The
$out
operator must be the last stage in the pipeline.Changed in version 3.2.0: MongoDB 3.2 added support for document validation. The
bypassDocumentValidation
field enables you to bypass document validation during the$out
phase of the aggregation operation. This lets you insert documents that do not meet the validation requirements. SpecifybypassDocumentValidation
as an option on the aggregation method or command.The
$out
stage has the following prototype form:{ $out: "<output-collection>" }
$out
takes a string that specifies the output collection name.Important
- You cannot specify a sharded collection as the output collection. The input collection for a pipeline can be sharded.
- The
$out
operator cannot write results to a capped collection.
Behaviors
Create New Collection
The $out
operation creates a new collection in the current database if one does not already exist. The collection is not visible until the aggregation completes. If the aggregation fails, MongoDB does not create the collection.
Replace Existing Collection
If the collection specified by the $out
operation already exists, then upon completion of the aggregation, the $out
stage atomically replaces the existing collection with the new results collection. Specifically, the $out
operation:
- Creates a temp collection.
- Copies the indexes from the existing collection to the temp collection.
- Inserts the documents into the temp collection.
- Calls
db.collection.renameCollection
withdropTarget: true
to rename the temp collection to the destination collection.
The $out
operation does not change any indexes that existed on the previous collection. If the aggregation fails, the $out
operation makes no changes to the pre-existing collection.
Example
A collection books
contains the following documents:
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
The following aggregation operation pivots the data in the books
collection to have titles grouped by authors and then writes the results to the authors
collection.
db.books.aggregate( [
{ $group : { _id : "$author", books: { $push: "$title" } } },
{ $out : "authors" }
] )
After the operation, the authors
collection contains the following documents:
{ "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }