[英]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'});
我希望所有的總和moneypaid
從collection1
具有isBook
真正的價值collection2
。
根據您的系統需求,我認為可以通過僅創建一個合並collection1
和collection2
所有屬性的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.