有没有 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 }
广告