简体   繁体   中英

Mongodb aggregation with 2 collections

In mongodb I have 2 collections like this

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

I want the sum of all moneypaid from collection1 which has isBook true value in collection2 .

Depending on what your system needs are, I think the model design could be simplified by creating just one collection that merges all the attributes in collection1 and collection2 . As an example:

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

in which you can then run the aggregation pipeline

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

However, with the current schema design you would have to first get the ids for collection1 which have isBook true value in collection2 and then use that id list as the $match query in the collection1 model aggregation, something like the following:

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

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