Pivot rows to columns in MongoDB

前端 未结 2 1308
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 04:32

The relevant question is Efficiently convert rows to columns in sql server. But the answer is specific to SQL.

I want the same result i.e. pivot row to column withou

相关标签:
2条回答
  • 2020-12-11 04:41

    Now, you can utilise new aggregation operator $arrayToObject to pivot MongoDB keys. This operator is available in MongoDB v3.4.4+

    For example, given an example data of:

    db.foo.insert({ provider: "Facebook", timestamp: '1371798000000', name: 'page_storytellers', value: 20871})
    db.foo.insert({ provider: "Facebook", timestamp: '1371798000000', name: 'page_fans', value: 1291509})
    db.foo.insert({ provider: "Facebook", timestamp: '1371798000000', name: 'page_fan_adds', value: 2829})
    db.foo.insert({ provider: "Google", timestamp: '1371798000000', name: 'page_fan_adds', value: 1000})
    

    You can utilise Aggregation Pipeline below:

    db.foo.aggregate([
      {$group:
         {_id:{provider:"$provider", timestamp:"$timestamp"}, 
          items:{$addToSet:{name:"$name",value:"$value"}}}
      }, 
      {$project:
         {tmp:{$arrayToObject: 
           {$zip:{inputs:["$items.name", "$items.value"]}}}}
      }, 
      {$addFields:
         {"tmp.provider":"$_id.provider", 
          "tmp.timestamp":"$_id.timestamp"}
      }, 
      {$replaceRoot:{newRoot:"$tmp"}
      }
    ]);
    

    The output would be:

    {
      "page_fan_adds": 1000,
      "provider": "Google",
      "timestamp": "1371798000000"
    },
    {
      "page_fan_adds": 2829,
      "page_fans": 1291509,
      "page_storytellers": 20871,
      "provider": "Facebook",
      "timestamp": "1371798000000"
    }
    

    See also $group, $project, $addFields, $zip, and $replaceRoot

    0 讨论(0)
  • 2020-12-11 04:46

    I have done something like this using aggregation. Could this help ?

    db.foo.insert({ timestamp: '1371798000000', propName: 'page_fans', propValue: 100})
    db.foo.insert({ timestamp: '1371798000000', propName: 'page_posts', propValue: 25})
    db.foo.insert({ timestamp: '1371798000000', propName: 'page_stories', propValue: 50})
    
    db.foo.aggregate({ $group: { _id: '$timestamp', result: { $push: { 'propName': '$propName', 'propValue': '$propValue' } }}})
    
    {
        "result" : [
            {
                "_id" : "1371798000000",
                "result" : [
                    {
                        "propName" : "page_fans",
                        "propValue" : 100
                    },
                    {
                        "propName" : "page_posts",
                        "propValue" : 50
                    },
                    {
                        "propName" : "page_stories",
                        "propValue" : 25
                    }
                ]
            }
        ],
        "ok" : 1
    }
    

    You may want to use $sum operator along the way. See here

    0 讨论(0)
提交回复
热议问题