我有这样的结构(还有一些其他类似的字段):
{
"_id" : 103803,
"views_count" : 20,
"views" : [
{
"date" : "2017-07-06",
"count" : 6
},
{
"date" : "2017-07-07",
"count" : 4
},
{
"date" : "2017-07-08”,
"count" : 10
},
],
"applications_count" : 30,
"applications" : [
{
"date" : "2017-07-06",
"count" : 5
},
{
"date" : "2017-07-07",
"count" : 15
},
{
"date" : "2017-07-08”,
"count" : 10
},
],
],
"publication_dates" : [
"2017-07-06",
"2017-07-07",
"2017-07-08",
"2017-07-09",
"2017-07-10",
],
},
{
"_id" : 103804,
"views_count" : 15,
"views" : [
{
"date" : "2017-07-06",
"count" : 5
},
{
"date" : "2017-07-07",
"count" : 5
},
{
"date" : "2017-07-08”,
"count" : 5
},
],
"applications_count" : 9,
"applications" : [
{
"date" : "2017-07-06",
"count" : 3
},
{
"date" : "2017-07-07",
"count" : 3
},
{
"date" : "2017-07-08”,
"count" : 3
},
],
],
"publication_dates" : [
"2017-07-05”,
"2017-07-06",
"2017-07-07",
"2017-07-08",
"2017-07-09",
"2017-07-10",
],
},
我想得到的结果是这样的:
[
{
_id: "2017-07-05”,
views: 0,
applications: 0,
},
{
_id: "2017-07-06”,
views: 11,
applications: 8,
},
{
_id: "2017-07-07”,
views: 9,
applications: 18,
},
….
]
我需要从publication_dates获取每个日期的视图和应用程序数。
我试过这样的查询,它看起来只适用于第一个$ group,进一步的结果是错误的
db.job_offer_stats.aggregate(
[
{
"$unwind":"$publication_dates"
},
{
"$unwind":"$views"
},
{
"$group":{
"_id":"$publication_dates",
"clicks":{
"$first":"$clicks"
},
"redirects":{
"$first":"$redirects"
},
"applications":{
"$first":"$applications"
},
"views_total":{
"$sum":{
"$cond":[
{
"$eq":[
"$views.date",
"$publication_dates"
]
},
"$views.count",
0
]
}
}
}
},
{
"$unwind":"$clicks"
},
{
"$group":{
"_id":"$_id",
"views_total":{
"$last":"$views_total"
},
"redirects":{
"$first":"$redirects"
},
"applications":{
"$first":"$applications"
},
"clicks_total":{
"$sum":{
"$cond":[
{
"$eq":[
"$clicks.date",
"$_id"
]
},
"$clicks.count",
0
]
}
}
}
},
{
"$unwind":"$redirects"
},
{
"$group":{
"_id":"$_id",
"views_total":{
"$last":"$views_total"
},
"clicks_total":{
"$last":"$clicks_total"
},
"applications":{
"$first":"$applications"
},
"redirects_total":{
"$sum":{
"$cond":[
{
"$eq":[
"$redirects.date",
"$_id"
]
},
"$redirects.count",
0
]
}
}
}
},
{
"$unwind":"$applications"
},
{
"$sort":{
"_id":1
}
},
{
"$group":{
"_id":"$_id",
"views_total":{
"$last":"$views_total"
},
"clicks_total":{
"$last":"$clicks_total"
},
"redirects_total":{
"$last":"$redirects_total"
},
"applications_total":{
"$sum":{
"$cond":[
{
"$eq":[
"$applications.date",
"$_id"
]
},
"$applications.count",
0
]
}
}
}
}
]
)
是否可以在单个查询中获得此类结果?
感谢您的任何建议。