Mongodb aggregate (count) on multiple fields simultaneously

前端 未结 2 543
耶瑟儿~
耶瑟儿~ 2020-12-24 02:57

I\'ve got documents that look like this:

{
    \"_id\" : \"someuniqueeventid\",
    \"event\" : \"event_type_1\",
    \"date\" : ISODate(\"2014-01-14T00:00:0         


        
2条回答
  •  难免孤独
    2020-12-24 03:35

    With MongoDb 3.4.4 and newer, you can leverage the use of $arrayToObject operator to get the counts. You would need to run the following aggregate pipeline:

    db.data.aggregate([
        { 
            "$group": {
                "_id": {
                    "event": "$event",
                    "day": { "$substr": [ { "$dayOfWeek": "$date" }, 0, -1 ] }
                },
                "count": { "$sum": 1 }
            }
        },
        { 
            "$group": {
                "_id": "$_id.event",
                "counts": {
                    "$push": {
                        "k": "$_id.day",
                        "v": "$count"
                    }
                }
            }
        },
        { 
            "$project": {
                "counts": { "$arrayToObject": "$counts" }
            } 
        }    
    ])
    

提交回复
热议问题