Saving the result of a MongoDB query

vorou picture vorou · Dec 25, 2013 · Viewed 16.7k times · Source

When doing a research in mongo shell I often write quite complex queries and want the result to be stored in other collection. I know the way to do it with .forEach():

db.documents.find(query).forEach(function(d){db.results.insert(d)})

But it's kind of tedious to write that stuff each time. Is there a cleaner way? I'd like the syntax to be something like db.documents.find(query).dumpTo('collectionName').

Answer

vorou picture vorou · Dec 25, 2013

Here's a solution I'll use: db.results.insert(db.docs.find(...).toArray())

There is still too much noise, though.

UPD: There is also an option to rewrite find using aggregation pipeline. Then you can use $out operator.