从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
}
}热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短