为其他字段的计数创建新字段

时间:2017-05-09 08:08:06

标签: mongodb mongoose mongodb-query aggregation-framework

我的数据库中有以下结构,为此我需要计算Tripduration并在每个"EndStation"下面引入一个新字段,这将给出"Tripcount" }基于Tripdurations

的数量
"_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
        ]
    }

我从以下查询开始,但是这个计算了所有tripdurations,它在顶部传递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,并将其作为新字段插入?

1 个答案:

答案 0 :(得分:1)

使用 $map 代替 $reduce ,如下所示:

db.mycollection.aggregate([
    {
        "$addFields": {            
            "Trips_out" : {
                "$map": {
                    "input": "$Trips_out",
                    "as": "trip",
                    "in": {
                        "EndStation" : "$$trip.EndStation",
                        "Tripcount": { "$size": "$$trip.Tripduration" },
                        "Tripduration": "$$trip.Tripduration"
                    }
                }
            }
        }
    }
])