MongoDB以一对多关系显示子项 [英] MongoDB Show children items in One to Many relationship
本文介绍了MongoDB以一对多关系显示子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是1:N关系的示例. 有一个根项目,由几个项目(子项)组成:
This is the example of 1: N relationship. There is a one root item which consists of the few items (children):
{
"_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"
]
}
我要做的是显示根项目中的子级数据:
What I want to do is to show children data from the root item:
{
"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
运算符执行这种情况:
I'm trying to perform this situation using $unwind
operator:
db.coll.aggregate([{ $unwind: "dates" }, { $unwind: "numbers" }, { $unwind: "goals" }, { $unwind: "durations"} ])
但查询未提供预期数据:/ 此处是很好的解决方案,但仅适用于两个数组.
but query doesn't give expected data :/ Here is the great solution, but works with only two arrays.
推荐答案
下面的管道应该给你这个想法
The following pipeline should give you the idea
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"] }
}
}
)
为您的示例产生以下输出
which produces the following output for your sample
/* 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"
}
这篇关于MongoDB以一对多关系显示子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文