我有一个像
这样的文档结构{
"id" : 123
"b" [
{
"dd" : 21,
"mm" : 05,
"yyyy" : 2015
"prod" : "xyz"
},
{
"dd" : 22,
"mm" : 05,
"yyyy" : 2015
"prod" : "abc"
}
]
},
{
"id" : 512
"b" [
{
"dd" : 11,
"mm" : 05,
"yyyy" : 2015
"prod" : "xdyz"
},
{
"dd" : 22,
"mm" : 05,
"yyyy" : 2015
"prod" : "abac"
}
]
},
.....
列表中的jsons表示日期。我如何获得所有文件中的日期计数?我想要像
那样的聚合计数2015-05-22 count: 2
2015-05-21 count: 1
2015-05-11 count: 1
答案 0 :(得分:3)
这应该有效。
db.Testing.aggregate([
{'$unwind': '$b'},
{ $project:
{ date:
{ $concat: [
{
"$substr": [ "$b.dd", 0, 2 ] }, "-", { "$substr": [ "$b.mm", 0, 2 ] }, "-", { "$substr": [ "$b.yyyy", 0, 4 ] }
]}
}
},
{'$group': {'_id':'$date','Count':{'$sum': 1}} }
])
结果:
{
"result" : [
{
"_id" : "11-5-2015",
"Count" : 1
},
{
"_id" : "22-5-2015",
"Count" : 2
},
{
"_id" : "21-5-2015",
"Count" : 1
}
],
"ok" : 1
}
答案 1 :(得分:0)
以下聚合框架将与您的需求紧密匹配:
db.collection.aggregate([
{
$unwind: "$b"
},
{
$group: {
_id: {
"dd" : "$b.dd",
"mm" : "$b.mm",
"yyyy" : "$b.yyyy"
},
count: { $sum: 1 }
}
}
]);
通过上述样本集合,您将获得以下聚合结果:
{
"result" : [
{
"_id" : {
"dd" : 22,
"mm" : 5,
"yyyy" : 2015
},
"count" : 2
},
{
"_id" : {
"dd" : 11,
"mm" : 5,
"yyyy" : 2015
},
"count" : 1
},
{
"_id" : {
"dd" : 21,
"mm" : 5,
"yyyy" : 2015
},
"count" : 1
}
],
"ok" : 1
}
如果数组元素字段值是字符串类型,那么您可以对 $project
管道阶段中的这些字段执行一些$concat
操作,以获得所需的输出