Mongodb汇总2个集合

在MongoDB中,我有2个这样的集合

var collection1Schema = new Schema({ moneyPaid:{ type:Number } }, {collection: 'collection1'}); var collection2 = new Schema({ coll_id: { type: Schema.ObjectId, ref: 'collection1' }, isBook: { type: Boolean, } }, {collection: 'collection2'}); 

我想要collection1中所有具有isBook真值的collection2的所有moneypaid的总和。

根据您的系统需要,我认为模型devise可以通过创build一个合并collection1collection2所有属性的collection1来简化。 举个例子:

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = new Schema({ moneyPaid:{ type: Number }, isBook: { type: Boolean, } }, {collection: 'account'}); var Account = mongoose.model('Account', accountSchema); 

您可以在其中运行聚合pipe道

 var pipeline = [ { "$match": { "isBook" : true } }, { "$group": { "_id": null, "total": { "$sum": "$moneyPaid"} } } ]; Account.aggregate(pipeline, function(err, results) { if (err) throw err; console.log(JSON.stringify(results, undefined, 4)); }); 

但是,对于当前的模式devise,您必须首先获取collection1中具有isBook true值的collection2 id,然后使用该id列表作为collection1模型聚合中的$match查询,如下所示:

 collection2Model.find({"isBook": true}).lean().exec(function (err, objs){ var ids = objs.map(function (o) { return o.coll_id; }), pipeline = [ { "$match": { "_id" : { "$in": ids } } }, { "$group": { "_id": null, "total": { "$sum": "$moneyPaid"} } } ]; collection1Model.aggregate(pipeline, function(err, results) { if (err) throw err; console.log(JSON.stringify(results, undefined, 4)); }); });