这是1:N关系的例子。 有一个根项目由少数项目(儿童)组成:
{
"_id" : ObjectId("52d017d4b60fb046cdaf4851"),
"dates" : [
1399518702000,
1399126333000,
1399209192000,
1399027545000
],
"dress_number" : "4",
"name" : "J. Evans",
"numbers" : [
"5982",
"5983",
"5984",
"5985"
],
"goals": [
"1",
"0",
"4",
"2"
],
"durations": [
"78",
"45",
"90",
"90"
]
}
我想要做的是显示来自根项目的子项数据:
{
"dates": "1399518702000",
"numbers": "5982",
"goals": "1",
"durations: "78"
},
{
"dates": "1399126333000",
"numbers": "5983",
"goals": "0",
"durations": "45"
},
{
"dates": "1399209192000",
"numbers": "5984",
"goals": "4",
"durations": "90"
},
{
"dates": "1399027545000",
"numbers": "5985",
"goals": "2",
"durations": "90"
}
在表格结构中看起来像:
根项:
name number
J. Evans 4
儿童用品
dates numbers goals durations
1399518702000 5982 1 78
1399126333000 5983 0 45
1399209192000 5984 4 90
1399027545000 5985 2 90
我尝试使用$unwind
运算符执行此操作:
db.coll.aggregate([{ $unwind: "dates" }, { $unwind: "numbers" }, { $unwind: "goals" }, { $unwind: "durations"} ])
但查询未提供预期数据:/ Here是一个很好的解决方案,但只能使用两个数组。
答案 0 :(得分:5)
以下管道应该给你一个想法
db.getCollection('yourCollection').aggregate(
{
$unwind: {
path: "$dates",
includeArrayIndex: "idx"
}
},
{
$project: {
_id: 0,
dates: 1,
numbers: { $arrayElemAt: ["$numbers", "$idx"] },
goals: { $arrayElemAt: ["$goals", "$idx"] },
durations: { $arrayElemAt: ["$durations", "$idx"] }
}
}
)
为您的样本生成以下输出
/* 1 */
{
"dates" : NumberLong(1399518702000),
"numbers" : "5982",
"goals" : "1",
"durations" : "78"
}
/* 2 */
{
"dates" : NumberLong(1399126333000),
"numbers" : "5983",
"goals" : "0",
"durations" : "45"
}
/* 3 */
{
"dates" : NumberLong(1399209192000),
"numbers" : "5984",
"goals" : "4",
"durations" : "90"
}
/* 4 */
{
"dates" : NumberLong(1399027545000),
"numbers" : "5985",
"goals" : "2",
"durations" : "90"
}