Javascript 如何从嵌套字段中获取数组的总和($sum)?

Javascript 如何从嵌套字段中获取数组的总和($sum)?,javascript,node.js,mongodb,mongoose,pug,Javascript,Node.js,Mongodb,Mongoose,Pug,我需要架构中嵌套的数组中所有元素的总和。 这是模式: const mongoose=require('mongoose'); 让historySchema=new mongoose.Schema({ 时间:{ 类型:字符串 } }) //用户模式 让userSchema=newmongoose.Schema({ 姓名:{ 类型:字符串, }, 出生日期:{ 类型:字符串, }, 电邮:{ 类型:字符串, }, 无人员限制:{ 类型:数字, 默认值:0 }, 详情:{ 类型:字符串, }, 地位:

我需要架构中嵌套的数组中所有元素的总和。 这是模式:

const mongoose=require('mongoose');
让historySchema=new mongoose.Schema({
时间:{
类型:字符串
}
})
//用户模式
让userSchema=newmongoose.Schema({
姓名:{
类型:字符串,
},
出生日期:{
类型:字符串,
},
电邮:{
类型:字符串,
},
无人员限制:{
类型:数字,
默认值:0
},
详情:{
类型:字符串,
},
地位:{
类型:布尔型,
默认值:false
},
时间:{
类型:数字,
默认值:0
},
超时:{
类型:数字,
默认值:0
},
时限:{
类型:数字,
默认值:0
},
历史:[{
时间:{
类型:编号
},
日期:{
类型:日期,
默认值:Date.now()
},
攀岩者:{
类型:编号
},
姓名:{
类型:字符串
}
}]
})
让User=module.exports=mongoose.model(“User”,userSchema);
Discusion中的嵌套字段为:

history:[{
    time:{
        type: Number
}]
查找方法是:

app.get('/user/:id',函数(req,res){
Users.findById(req.params.id,函数(err,Users){
res.render(“用户”,
{
标题:users.name,
用户:用户,,
});
})
})
我是否可以在查找路径上附加一个带有
$sum
的聚合,以便将带有sum的数据发送到渲染视图


例如,
totalTimeHistory:$sum aggregate data

使用以下代码段:

const result = Users.aggregate([
{
   $match: {
     //Your find block here
   }
},
{
    $unwind: "$history"
},
{
    $project: {
        totalTimeHistory: { $sum: "$history.time"}
    }
}
])
请尝试以下查询:

db.collection.aggregate([
{
“$match”:{
“名称”:“名称”//或您想要的任何内容
}
},
{
“$project”:{
“总数”:{
$sum:“$history.time”
}
}
}
])
这样,您就不需要
$unwind

示例

db.getCollection('users').aggregate([
{
$match:{
}
},
{
$unwind:“$history”
},
{
$group:{
_id:,
历史记录:{$push:“$$ROOT.history”}
}
},
{
$addFields:{
TotalSumHistoryTypes:{$sum:$history.type}
}
},
])

您的输出将如下所示

说明:

$match:在集合中查找

$unwind:展开历史记录数组,以便对历史记录的值进行分组

$group:这里我们创建了一个名为history的数组,并将history对象($$ROOT.history)推入其中

$addfield:用于添加架构中不存在的新字段


希望这能解释欢呼声

这能回答你的问题吗?
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" }
    }
},