我想基于数组索引从一个集合中加入两个数组,而不是(主)键。
数据如下所示:
{"_id" : ObjectId("1"),
"clicks" : {
"cumulative" : {
"data" : [
3,
7,
8
]
},
"daily" : {
"data" : [
3,
4,
1
]
}
},
"websiteId" : "abcdef"
"day" : {
"isoDate" : [
ISODate("2016-07-07T02:00:00.000+02:00"),
ISODate("2016-07-08T02:00:00.000+02:00"),
ISODate("2016-07-09T02:00:00.000+02:00")
]}
},
....
我想基于每个数组的索引加入day.isoDate和clicks.cumulative.data。该表应如下所示:
ObjectID Date Clicks
1 2016-07-07 3
1 2016-07-08 7
1 2016-07-09 8
到目前为止我尝试了什么:
db.collection1.aggregate([
{$unwind: "$day.isoDate"},
{$match: {"websiteId": "abcdef"} },
{$group: {_id: "$day.isoDate.Value"}}
])
有人有建议吗?
答案 0 :(得分:1)
这可以通过告诉mongodb存储unwinded数组的索引然后在投影中使用它来实现:
db.test.aggregate([
{"$unwind": {
path: "$day.isoDate",
includeArrayIndex: "index"
}},
{"$project": {
"Date" : "$day.isoDate",
"Clicks": {
"$arrayElemAt" : [
"$clicks.cumulative.data",
"$index"
]
}}
}])
这将输出
{ "_id" : ObjectId("5910de2e92842f684b605965"), "Date" : ISODate("2016-07-07T00:00:00Z"), "Clicks" : 3 }
{ "_id" : ObjectId("5910de2e92842f684b605965"), "Date" : ISODate("2016-07-08T00:00:00Z"), "Clicks" : 7 }
{ "_id" : ObjectId("5910de2e92842f684b605965"), "Date" : ISODate("2016-07-09T00:00:00Z"), "Clicks" : 8 }
>