【发布时间】:2017-05-09 16:21:06
【问题描述】:
我的数据库中有以下结构,为此我需要计算Tripduration 并在每个相应的"EndStation" 下方引入一个新字段,根据Tripdurations 的数量给出"Tripcount" .
"_id": 1,
"Tripcount": 4,
"Trips_out": [
{
"EndStation": 3119,
"Tripcount": // This should be 3
"Tripduration": [
544,
364,
34
]
},
{
"EndStation": 3081,
"Tripcount": // This should be 1
"Tripduration": [
835
]
}
我从以下查询开始,但这个查询是针对所有行程持续时间计算的,它在顶部提供 Tripcount : 4:
db.mycollection.aggregate(
[
{
"$addFields":{
"Tripcount":{
"$reduce":{
"input":{
"$map":{
"input":"$Trips_out",
"in":{
"$size":"$$this.Tripduration"
}
}
},
"initialValue":0,
"in":{
"$add":[
"$$value",
"$$this"
]
}
}
}
}
}
]
)
如何对其进行修改,以便计算每个 EndStation 的 Tripdurations,并将其作为新字段插入?
【问题讨论】:
标签: mongodb mongoose mongodb-query aggregation-framework