【问题标题】:Create new field for count of other field为其他字段的计数创建新字段
【发布时间】: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


    【解决方案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"
                        }
                    }
                }
            }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 2016-08-06
      • 2016-06-15
      相关资源
      最近更新 更多