Project array of Objects to Key Value

前端 未结 1 628
南方客
南方客 2021-01-27 12:48

After aggregations i get this result,

{
    \"_id\" : {
        \"date\" : ISODate(\"2017-08-30T00:00:00.000Z\")
    },
    \"aggr\" : [ 
        {
            \         


        
相关标签:
1条回答
  • 2021-01-27 13:16

    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" }
              }}
            ]
          }
        }    
      }}
    ])
    

    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 }),{}
        )
      )
    )
    
    0 讨论(0)
提交回复
热议问题