问题描述
我需要在我的模式中嵌套的数组中所有元素的总和。 这是模式:
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,timeFinal:{
type: Number,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
示例here
,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:在这里,我们创建了一个称为历史的数组,并将历史对象($$ ROOT.history)压入其中。
$ addFiled:用于添加模式中不存在的新字段
希望这可以说明欢呼声