How to store query output in temp MongoDB database?

To store query output in a temporary MongoDB database, use forEach() to iterate through query results and insert() each document into a new collection. This technique allows you to copy data between collections or create temporary datasets for processing.

Syntax

db.sourceCollection.find().forEach(function(document) { 
    db.tempCollection.insert(document); 
});

Create Sample Data

db.demo43.insertMany([
    {"StudentName": "Chris"},
    {"StudentName": "Bob"}, 
    {"StudentName": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e25d4b3cfb11e5c34d898e5"),
        ObjectId("5e25d4b8cfb11e5c34d898e6"),
        ObjectId("5e25d4bbcfb11e5c34d898e7")
    ]
}

Example: Copy Data to Temporary Collection

Display the original collection ?

db.demo43.find();
{"_id": ObjectId("5e25d4b3cfb11e5c34d898e5"), "StudentName": "Chris"}
{"_id": ObjectId("5e25d4b8cfb11e5c34d898e6"), "StudentName": "Bob"}
{"_id": ObjectId("5e25d4bbcfb11e5c34d898e7"), "StudentName": "David"}

Copy all documents to a temporary collection ?

db.demo43.find().forEach(function(myDocument) { 
    db.demo44.insert(myDocument); 
});

Verify the data was copied to the temporary collection ?

db.demo44.find();
{"_id": ObjectId("5e25d4b3cfb11e5c34d898e5"), "StudentName": "Chris"}
{"_id": ObjectId("5e25d4b8cfb11e5c34d898e6"), "StudentName": "Bob"}
{"_id": ObjectId("5e25d4bbcfb11e5c34d898e7"), "StudentName": "David"}

Key Points

  • The forEach() method executes a function for each document in the result set.
  • Original _id values are preserved during the copy operation.
  • Use insertMany() with an array for better performance with large datasets.

Conclusion

The forEach() method combined with insert() provides a simple way to copy query results to temporary collections. This approach is useful for data backup, transformation, or creating temporary datasets for analysis.

Updated on: 2026-03-15T02:48:36+05:30

793 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements