MongoDB 如何按子文件匹配排序?
要按子文件匹配排序,可以使用聚合框架。讓我們首先建立一個帶有文件的集合 -
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Chris",
"StudentDetails": [
{
"Age":21,
"StudentScore":91
},
{
"Age":22,
"StudentScore":99
},
{
"Age":21,
"StudentScore":93
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd57e297924bb85b3f48942")
}
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Robert",
"StudentDetails": [
{
"Age":24,
"StudentScore":78
},
{
"Age":21,
"StudentScore":86
},
{
"Age":23,
"StudentScore":45
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd57e4c7924bb85b3f48943")
}以下查詢使用 find() 方法從集合中顯示所有文件 -
> db.sortBySubDocumentsDemo.find().pretty();
這將產生以下輸出 -
{
"_id" : ObjectId("5cd57e297924bb85b3f48942"),
"StudentName" : "Chris",
"StudentDetails" : [
{
"Age" : 21,
"StudentScore" : 91
},
{
"Age" : 22,
"StudentScore" : 99
},
{
"Age" : 21,
"StudentScore" : 93
}
]
}
{
"_id" : ObjectId("5cd57e4c7924bb85b3f48943"),
"StudentName" : "Robert",
"StudentDetails" : [
{
"Age" : 24,
"StudentScore" : 78
},
{
"Age" : 21,
"StudentScore" : 86
},
{
"Age" : 23,
"StudentScore" : 45
}
]
}以下查詢按子文件匹配排序。此處,我們按 StudentScore 排序 -
> db.sortBySubDocumentsDemo.aggregate([
{$match: { 'StudentDetails.Age': 21 }},
{$unwind: '$StudentDetails'},
{$match: {'StudentDetails.Age': 21}},
{$project: {_id: 0, "StudentName": 1, 'StudentDetails.StudentScore': 1}},
{$sort: { 'StudentDetails.StudentScore': 1 }},
{$limit: 5}
]);這將產生以下輸出 -
{ "StudentName" : "Robert", "StudentDetails" : { "StudentScore" : 86 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 91 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 93 } }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP