如何从 MongoDB 文档中的子数组中查找最高值?
要从文档中的子数组中查找最高值,可以使用集合框架。我们首先使用文档创建一个集合
> db.findHighestValueDemo.insertOne( ... { ... _id: 10001, ... "StudentDetails": [ ... { "StudentName": "Chris", "StudentMathScore": 56}, ... { "StudentName": "Robert", "StudentMathScore":47 }, ... { "StudentName": "John", "StudentMathScore": 98 }] ... } ... ); { "acknowledged" : true, "insertedId" : 10001 } > db.findHighestValueDemo.insertOne( ... { ... _id: 10002, ... "StudentDetails": [ ... { "StudentName": "Ramit", "StudentMathScore": 89}, ... { "StudentName": "David", "StudentMathScore":76 }, ... { "StudentName": "Bob", "StudentMathScore": 97 } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 10002 }
以下是使用 find() 方法从集合中显示所有文档的查询
> db.findHighestValueDemo.find().pretty();
这将产生以下输出
{ "_id" : 10001, "StudentDetails" : [ { "StudentName" : "Chris", "StudentMathScore" : 56 }, { "StudentName" : "Robert", "StudentMathScore" : 47 }, { "StudentName" : "John", "StudentMathScore" : 98 } ] } { "_id" : 10002, "StudentDetails" : [ { "StudentName" : "Ramit", "StudentMathScore" : 89 }, { "StudentName" : "David", "StudentMathScore" : 76 }, { "StudentName" : "Bob", "StudentMathScore" : 97 } ] }
以下是从文档中的子数组中查找最高值的查询
> db.findHighestValueDemo.aggregate([ ... {$project:{"StudentDetails.StudentName":1, "StudentDetails.StudentMathScore":1}}, ... {$unwind:"$StudentDetails"}, ... {$sort:{"StudentDetails.StudentMathScore":-1}}, ... {$limit:1} ... ]).pretty();
这将产生以下输出
{ "_id" : 10001, "StudentDetails" : { "StudentName" : "John", "StudentMathScore" : 98 } }
广告