Reputation: 190
Does anybody know how one would go about using the $out operator to push the results of a MongoDB aggregation function into a new collection in node.js?
This is what I have:
var fs = require('fs');
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
var createGroups = function(db, callback) {
db.collection('people').aggregate(
[
{ $group: { "_id": "$code", "sendees" : {$push : "$email"}, "count": { $sum: 1 } } }
]
).toArray(function(err, result) {
assert.equal(err, null);
console.log(result);
callback(result);
});
};
MongoClient.connect('mongodb://localhost:12121/systest', function(err, db) {
assert.equal(null, err);
createGroups(db, function() {
db.close();
});
});
Which outputs to the console fine, exactly as I'd expect - but I'm having little luck trying to export this to a new collection.
Thanks!
Upvotes: 2
Views: 2473
Reputation: 190
Thanks for your answers folks - both very helpful. As it happens I was using an outdated version of mongo from before $out came into being - but once I sorted this out and did as you suggested above it worked perfectly.
Upvotes: 0
Reputation: 103335
You could try use the mongo-aggregate-out package which saves aggregation results to a collection for Mongo versions < 2.6. If your MongoDB version is 2.6 or newer, the module would behave as passthrough and will use the native feature:
var aggregateOut = require('mongo-aggregate-out'),
pipelineArray = [
{
$group: {
"_id": "$code",
"sendees" : {$push : "$email"},
"count": { $sum: 1 }
}
}
];
var createGroups = function(db, callback) {
aggregateOut(db.collection('people'), pipelineArray, { out: "newCollection"},
function (err) {
assert.equal(err, null);
var cur = db.collection('newCollection').find();
callback(cur);
});
};
Upvotes: 0