从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 } }