[英]How can I get the total sum ($sum) of an array from a nested field?
I need the total sum of all the elements in an array that is nestet in my schema.我需要在我的模式中嵌套的数组中所有元素的总和。 This is the schema:这是架构:
const mongoose = require('mongoose');
let historySchema = new mongoose.Schema({
time: {
type:String
}
})
//users schema
let userSchema = new mongoose.Schema({
name:{
type:String,
},
dob:{
type:String,
},
email:{
type:String,
},
noOfpeopleClimbing:{
type: Number,
default:0
},
details:{
type:String,
},
status:{
type: Boolean,
default: false
},
timeIn:{
type: Number,
default: 0
},
timeOut:{
type: Number,
default: 0
},
timeFinal:{
type: Number,
default: 0
},
history:[{
time:{
type: Number
},
date:{
type:Date,
default:Date.now()
},
climbers:{
type: Number
},
names:{
type: String
}
}]
})
let User = module.exports = mongoose.model("User", userSchema);
The nested field in disscusion is:讨论中的嵌套字段是:
history:[{
time:{
type: Number
}]
And the find method is:查找方法是:
app.get('/user/:id', function(req,res){
Users.findById(req.params.id, function(err, users){
res.render("user",
{
title:users.name,
users:users,
});
})
})
Can I attach to my find route an aggregate with $sum
in order for me to send the data with the sum to my render view?.我可以将带有$sum
的聚合附加到我的查找路由,以便我将带有总和的数据发送到我的渲染视图吗?
For example totalTimeHistory:$sum aggregate data
.例如totalTimeHistory:$sum aggregate data
。
Use the following snippet below:使用以下代码段:
const result = Users.aggregate([
{
$match: {
//Your find block here
}
},
{
$unwind: "$history"
},
{
$project: {
totalTimeHistory: { $sum: "$history.time"}
}
}
])
db.getCollection('users').aggregate([
{
$match: {
<your find query goes here>
}
},
{
$unwind: '$history'
},
{
$group: {
_id: <your user object id (or) null>,
history: { $push: "$$ROOT.history" }
}
},
{
$addFields: {
totalSumOfHistoryTypes: { $sum: "$history.type" }
}
},
]) ])
your output will look like你的输出看起来像
explanation:解释:
$match: to find in the collection $match:在集合中查找
$unwind: to unwind the history array so that the values of history can be grouped $unwind: 展开历史数组,以便历史的值可以分组
$group: here we have created an array called history and pushed the history object($$ROOT.history) into it $group:这里我们创建了一个名为 history 的数组并将历史对象($$ROOT.history)推入其中
$addFiled: used to add a new field which is not present on the schema $addFiled:用于添加架构中不存在的新字段
Hope this explains cheers希望这能解释欢呼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.