$out
The $out
operator is used in a MongoDB aggregation pipeline to write the result of the aggregation to a specified collection. The $out
stage must be the last stage in the pipeline, and it effectively replaces the existing collection with the new one containing the aggregated results. If the specified collection does not exist, MongoDB will create it.
Syntax
Here's the basic syntax of the $out
operator:
{
$out: "target_collection_name"
}
Example
Let's say you have a students
collection with the following documents:
[
{ "_id": 1, "name": "Alice", "score": 90 },
{ "_id": 2, "name": "Bob", "score": 85 },
{ "_id": 3, "name": "Charlie", "score": 92 }
]
You want to create a new collection that contains only the students who scored more than 88. You can use the $out
operator to achieve this:
db.students.aggregate([
{
$match: { score: { $gt: 88 } }
},
{
$out: "high_scorers"
}
]);
After running this aggregation, a new collection named high_scorers
will be created with the following documents:
[
{ "_id": 1, "name": "Alice", "score": 90 },
{ "_id": 3, "name": "Charlie", "score": 92 }
]
Considerations
The
$out
operator replaces the target collection entirely. Any existing data in the target collection will be lost.The
$out
stage must be the last stage in the aggregation pipeline.The operation is atomic; it provides a consistent snapshot of the data.
Indexes from the source collection are not copied to the target collection. You'll need to recreate any indexes that you need on the new collection.
The
$out
operator can also be used to write results to a different database by specifying a fully qualified namespace (database.collection
).
Use Cases
Data Archiving: You can use
$out
to archive data by writing older records to a separate collection.Reporting: Generate complex reports and store them in a separate collection for quick access.
Data Transformation: Perform complex transformations on your data and store the results in a new collection.