![](/img/trans.png)
[英]How can I get a sum total from a field that is part of a dynamic row add?
[英]How can I get the total sum ($sum) of an array from a nested field?
我需要在我的模式中嵌套的数组中所有元素的总和。 这是架构:
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);
讨论中的嵌套字段是:
history:[{
time:{
type: Number
}]
查找方法是:
app.get('/user/:id', function(req,res){
Users.findById(req.params.id, function(err, users){
res.render("user",
{
title:users.name,
users:users,
});
})
})
我可以将带有$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": {
"name": "name" //or whatever you want
}
},
{
"$project": {
"total": {
"$sum": "$history.time"
}
}
}
])
这样你就不需要$unwind
示例在这里
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" }
}
},
])
解释:
$match:在集合中查找
$unwind: 展开历史数组,以便历史的值可以分组
$group:这里我们创建了一个名为 history 的数组并将历史对象($$ROOT.history)推入其中
$addFiled:用于添加架构中不存在的新字段
希望这能解释欢呼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.