Count aggregation base on key value and make keys become values in mongoDB

db.collection.aggregate([
    { $addFields: {
        data: { $arrayElemAt: ['$data', 0] } // OR data: { $first: '$data' }
    } },
    { $addFields: {
        name: '$data.name',
        date_key: {
            $map: {
                input: { $objectToArray: '$data.in_data.date' },
                in: '$$this.k'
            }
        }
    } },
    { $group: {
        _id: '$typ',
        typ_count: { $sum: 1 },
        name: { $push: '$name' },
        date_key: { $push: '$date_key' }
    } },
    { $project: {
       _id: 0,
        typ_count: 1,
        name: 1,
        date_key: {
            $reduce: {
                input: '$date_key',
                initialValue: [],
                in: { 
                    $concatArrays: [ 
                        '$$value', 
                        {
                            $cond: [
                                { $in: ["$$this", ["$$value"]] },
                                [], 
                                "$$this"
                            ]
                        } 
                    ]  
                }                
            }
        }
    } }
])
Topics: MongoDB

Related Code Examples