是否有MongoDB查询来连接深层子列表?
使用aggregate()$unwind连接深层子列表。让我们创建一个包含文档的集合-
> db.demo70.insertOne(
... {
...
... "first" : [
... {
... "details" : {
... "second" : [
... {
... "StudentDetails" : {
... "Score" : 10
... }
... },
... {
... "StudentDetails" : {
... "Score" : 20
... }
... },
... {
... "StudentDetails" : {
... "Score" : 30
... }
... }
... ]
... }
... },
... {
... "details" : {
... "second" : [
... {
... "StudentDetails" : {
... "Score" : 11
... }
... },
... {
... "StudentDetails" : {
... "Score" : 18
... }
... },
... {
... "StudentDetails" : {
... "Score" : 29
... }
... }
... ]
... }
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29ad4d0912fae76b13d76d")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo70.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5e29ad4d0912fae76b13d76d"),
"first" : [
{
"details" : {
"second" : [
{
"StudentDetails" : {
"Score" : 10
}
},
{
"StudentDetails" : {
"Score" : 20
}
},
{
"StudentDetails" : {
"Score" : 30
}
}
]
}
},
{
"details" : {
"second" : [
{
"StudentDetails" : {
"Score" : 11
}
},
{
"StudentDetails" : {
"Score" : 18
}
},
{
"StudentDetails" : {
"Score" : 29
}
}
]
}
}
]
}以下是连接深层子列表的查询-
> db.demo70.aggregate([
... { $unwind: "$first" },
... { $unwind: "$first.details.second" },
... { $sort: { "first.details.second.StudentDetails.Score": -1 } },
... { $limit: 3 },
... { $replaceRoot: { newRoot: "$first.details.second.StudentDetails" } },
... { $sort: { "Score": 1 } }
... ]);这将产生以下输出-
{ "Score" : 20 }
{ "Score" : 29 }
{ "Score" : 30 }热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿