将对象项目数组转换为键值 [英] Project array of Objects to Key Value

查看:68
本文介绍了将对象项目数组转换为键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

汇总后我得到这个结果,

After aggregations i get this result,

{
    "_id" : {
        "date" : ISODate("2017-08-30T00:00:00.000Z")
    },
    "aggr" : [ 
        {
            "gender" : "unknown",
            "count" : 365
        }, 
        {
            "gender" : "male",
            "count" : 2
        }
    ]
}

是否可以将其转换为以下格式

Is it possible to convert this into below format

{
    "date" : ISODate("2017-08-30T00:00:00.000Z"),
    "unknown" : 365,
    "male" : 2
}

尝试使用 $ unwind $ project ,但无法将数组对象转换为键值对

Tried using $unwind and $project, but couldn't convert array objects into key,value pairs

推荐答案

是的,使用 $ arrayToObject $ map 将现有数组转换为它接受的格式:

Yes, using $arrayToObject and $map to convert the existing array to a format it accepts:

db.collection.aggregate([
  { "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": {
        "$concatArrays": [
          [{ "k": "date", "v": "$_id.date" }],  
          { "$map": {
            "input": "$aggr",
            "in": { "k": "$$this.gender", "v": "$$this.count" }
          }}
        ]
      }
    }    
  }}
])

当然,如果这实际上只是在现有聚合的尾部而你至少没有MongoDB 3.4.4引入运算符,然后您可以简单地将结果重新整形为客户端代码:

Of course if this is actually only on the "tail" of an existing aggregation and you don't have at least MongoDB 3.4.4 where the operator is introduced, then you can simply reshape the result in the client code:

db.collection.aggregate([
  // existing pipeline
]).map(d => 
  Object.assign(
    { date: d._id.date },
    d.aggr.reduce((acc,curr) =>
      Object.assign(acc,{ [curr.gender]: curr.count }),{}
    )
  )
)

这篇关于将对象项目数组转换为键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆