是否有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 }