Pivot rows to columns in MongoDB

前端 未结 2 1317
隐瞒了意图╮
隐瞒了意图╮ 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: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

提交回复
热议问题