Export mongodb aggregation framework result to a n

2019-01-11 04:13发布

问题:

I want to save the aggregation framework result to a new collection. I know that's impossible with the framework at the moment with the command itself.

Is there a workaround in the shell?

回答1:

Update: See Salvador's answer for a more efficient way to do this in MongoDB 2.6+.


Save the aggregation result in a variable and then insert its result property into a new collection:

var result = db.foo.aggregate(...);
db.bar.insert(result.result);


回答2:

Starting with Mongo 2.6.0 you can do this natively without any additional manipulation.

db.<collection>.aggregate( [
     { <operation> },
     { <operation> },
     ...,
     { $out : "<output-collection>" }
] )

Check the new aggregation operator $out for more detailed example.

P.S. using this way you are not limited to 16Mb size.



回答3:

result.result is no longer working, try toArray().

var result  = db.coll.aggregate(...);
db.bar.insert(result.toArray());