简体   繁体   中英

Mongo: Import results of an aggregate query?

Sorry for the basic question, I'm new to mongo and learning my way around.

I have run an aggregate query in Mongo:

> var result = db.urls.aggregate({$group : {_id : "$pagePath"} });
> result
{ "_id" : "/section1/page1" }
{ "_id" : "/section1/page2" }
...
Type "it" for more

I would now like to save the results of this aggregate query into a new collection. This is what I've tried:

> db.agg1.insert(result);
WriteResult({ "nInserted" : 1 })

But this seems to have inserted all the rows as just one row:

> db.agg1.count()
1
> db.agg1.findOne();
{ "_id" : "/section1/page1" }
{ "_id" : "/section1/page2" }
...
Type "it" for more

How can I insert these as separate rows?

I've tried inserting the _id directly, without success:

> db.agg1.insert(result._id);
2014-12-17T15:23:26.679+0000 no object passed to insert! at src/mongo/shell/collection.js:196

Use the $out pipeline operator for that:

db.urls.aggregate([
    {$group : {_id : "$pagePath"} },
    {$out: "agg1"}
]);

Note that $out was added in MongoDB 2.6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM