我的文档具有这种结构
_id: "adklkj389723jk23KLJjl2LU92kJO387"
"impressions": [{
"_id": ObjectId("5b74799535f2722494075981"),
"country": "GB",
"impression_count": 22,
"_campaignid": ObjectId("5b72d78847db422040ee60cf"),
"date": ISODate("2018-08-15T19:00:00Z")
},
{
"_id": ObjectId("5b74799d35f2722494075982"),
"country": "GB",
"impression_count": 22,
"_campaignid": ObjectId("5b72d7bf47db422040ee60d1"),
"date": ISODate("2018-08-15T19:00:00Z")
},
{
"_id": ObjectId("5b7479a735f2722494075983"),
"country": "GB",
"impression_count": 20,
"_campaignid": ObjectId("5b72d79e47db422040ee60d0"),
"date": ISODate("2018-08-15T19:00:00Z")
}
]
我想做什么 我想用印象创建的日期将印象分组,我将日期另存为db中的字符串以执行此操作,我正在使用此查询
db.advertisers.aggregate([{
$group: {
_id: "$impressions.date",
count: {
$sum: "$impressions.impression_count"
}
}
}]).pretty()
结果
此查询给我的结果是这样,我在做什么错了?
{
"_id": [
ISODate("2018-08-15T19:00:00Z"),
ISODate("2018-08-15T19:00:00Z"),
ISODate("2018-08-15T19:00:00Z")
],
"count": 1
}
答案 0 :(得分:1)
由于要处理数组,因此可能需要unwind
impressions
:
db.collection.aggregate([
{
"$unwind": "$impressions"
},
{
$group: {
_id: "$impressions.date",
count: {
$sum: "$impressions.impression_count"
},
}
}
])
这会给你:
[
{
"_id": ISODate("2018-08-15T19:00:00Z"),
"count": 64
}
]
您可以see this here。