[英]MongoDB aggregate return count of 0 if no results
I have the following MongoDB query that groups by date and result and gives a count. 我有以下MongoDB查询按日期和结果分组并给出计数。 I'd like to have the query also return a count of 0 for a particular date and result if data doesn't exist for that day.
我希望查询还为特定日期返回0,如果当天不存在数据,则返回结果。
For example I have the following result statuses: SUCCESS and FAILED. 例如,我有以下结果状态:SUCCESS和FAILED。 If on the 21st there were no results of FAILED I would want a count returned of 0:
如果在21日没有FAILED的结果我想要一个返回0的计数:
{
"_id" : {
"month" : 1,
"day" : 21,
"year" : 2014,
"buildResult" : "FAILURE"
},
"count" : 0
}
I've done something similar with a relational database and a calendar table, but I'm not sure how to approach this with MongoDB. 我已经使用关系数据库和日历表做了类似的事情,但我不确定如何使用MongoDB来解决这个问题。 Is this possible or should I do something programatically after running the query?
这是可能的,还是应该在运行查询后以编程方式执行某些操作?
Here is an example of a document (simplified) in the database: 以下是数据库中文档(简化)的示例:
{
"_id" : ObjectId("52deab2fe4b0a491abb54108"),
"type" : "build",
"time" : ISODate("2014-01-21T17:15:27.471Z"),
"data" : {
"buildNumber" : 43,
"buildDuration" : 997308,
"buildResult" : "SUCCESS"
}
}
Here is my current query: 这是我目前的查询:
db.builds.aggregate([
{ $match: { "data.buildResult" : { $ne : null} }},
{ $group: {
_id: {
month: { $month: "$time" },
day: { $dayOfMonth: "$time" },
year: { $year: "$time" },
buildResult: "$data.buildResult",
},
count: { $sum: 1}
} },
{ $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1} }
])
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. 您希望从输出中获取更多输入文档,只能使用与数组一起使用的
unwind
运算符,但您没有任何数组,因此我知道在您的情况下无法获取更多文档。 So you should add some logic after query result to create new data for existing dates with 0 count for another type of buildResult... 因此,您应该在查询结果之后添加一些逻辑,以便为现有日期创建新数据,并为另一种类型的buildResult创建0计数...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.