MongoDB aggregate return count of 0 if no results

前端 未结 1 779
广开言路
广开言路 2021-02-15 10:19

I have the following MongoDB query that groups by date and result and gives a count. I\'d like to have the query also return a count of 0 for a particular date and result if da

1条回答
  •  南方客
    南方客 (楼主)
    2021-02-15 11:15

    If I correctly understand what do you want, you could try this:

    db.builds.aggregate([
        { $project: 
            { 
                time: 1,
                projectedData: { $ifNull: ['$data.buildResult', 'none'] } 
            } 
        },
    
        { $group: { 
            _id: { 
                month: { $month: "$time" },
                day: { $dayOfMonth: "$time" },
                year: { $year: "$time" }, 
                buildResult: "$projectedData"
            },
            count: { $sum: { $cond: [ { $eq: [ "$projectedData", "none" ] }, 0, 1 ] } }
        } },
    
        { $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } }
    ])
    

    Update:
    You want to get from output more documents that been in input, it is possible only with unwind operator that works with arrays, but you haven't any arrays, so as I know it is impossible to get more documents in your case. So you should add some logic after query result to create new data for existing dates with 0 count for another type of buildResult...

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