猫鼬中的人口+聚集 [英] Populate + Aggregate in Mongoose
问题描述
我有两种Mongoose模型:一种用于交易,另一种用于与之关联的标签.为了实施一些报告,我需要像这样的聚合代码:
I have two Mongoose models: one for transactions and the other one for the tags associated with them. In order to implement some reports, I need aggregate code like this:
Transaction.aggregate([
{ $unwind: '$tags' },
{
$group: {
_id: '$tags',
amount: {
$sum: '$amount'
}
}
}
])
问题
这将产生包含_id
和amount
的输出.现在,我想从模型中填充其他字段(例如name
),并保留计算出的amount
列.我可以在一个简单的populate
内做到这一点吗?
Question
This produces output containing _id
and amount
. Now, I'd like to populate the other fields (e.g. name
) from the model, keeping the calculated amount
column. Can I do that within a simple populate
?
我正在描述的模型的模式:
The schemas for the models I'm describing:
var TransactionSchema = new Schema({
description: {
type: String,
trim: true
},
amount: {
type: Number,
required: 'Forneça um valor',
},
date: {
type: Date,
required: 'Forneça uma data',
default: Date.now
},
fromOfx: {
type: Boolean,
default: false
},
created: {
type: Date,
default: Date.now
},
correlated: {
type: Boolean,
default: false
},
tags: [{
type: Schema.Types.ObjectId,
ref: 'TransactionTag'
}],
correlates: [{
type: Schema.Types.ObjectId,
ref: 'Transaction'
}],
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});
var TransactionTagSchema = new Schema({
name: {
type: String,
required: 'Forneça um nome',
trim: true
},
description: {
type: String,
trim: true
},
amount: {
type: Number
}
});
推荐答案
从MongoDB中获取数据后,您可以填充聚合.看起来像这样:
You can populate an aggregation after you fetched the data from the MongoDB. This will look something like this:
// Your aggregate query from your question
Transaction.aggregate([{
$unwind: '$tags'
}, {
$group: {
_id: '$tags',
amount: {
$sum: '$amount'
}
}
}])
.exec(function(err, transactions) {
// Don't forget your error handling
// The callback with your transactions
// Assuming you are having a Tag model
Tag.populate(transactions, {path: '_id'}, function(err, populatedTransactions) {
// Your populated translactions are inside populatedTransactions
});
});
这篇关于猫鼬中的人口+聚集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!