繁体   English   中英

Mongodb聚合有2个集合

[英]Mongodb aggregation with 2 collections

在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'});

我希望所有的总和moneypaidcollection1具有isBook真正的价值collection2

根据您的系统需求,我认为可以通过仅创建一个合并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);

然后,您可以在其中运行聚合管道

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));
});

然而,目前的架构设计,你必须首先获得其在isBook真值collection1的ID collection2 ,然后使用该ID列表作为$match查询在collection1模型聚集,类似如下:

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));
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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