$out (Output)
Last updated: 2026-10-09
$out (Output)
$out writes pipeline results to a named collection, replacing all of its previous contents; the target is auto-created if missing. It must be the final stage and cannot be combined with $merge. It takes a collection-level lock and fully replaces data, so it suits offline reports and cache tables. $out gained cross-database writes in MongoDB 4.4.
| Category | Advanced & Diagnostic |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $out: "<collection>" }
⚙️ Parameters
| target collection | Name of the collection to write into. |
|---|
Returns:No documents continue; results are written to the target collection
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $out: export 2024 orders to a new collection
db.orders.aggregate([
{ $match: { year: 2024 } },
{ $out: 'orders_2024' }
])
Output:
// orders_2024 is fully replaced
📌 Notes
- Must be the final pipeline stage
- The target collection is fully replaced, not appended
- A collection-level lock during write blocks concurrent operations on large datasets
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QDoes $out overwrite an existing collection?
AYes, the whole collection is replaced; on failure the original is kept.
QShould I use $out or $merge?
AUse $out for full replacement; $merge for incremental updates and key-based merging.
QCan $out write to another database?
ASince MongoDB 4.4, write it as 'otherdb.coll'.