在 MongoDB 中按子文件排序
要按子文件進行排序,請在 MongoDB 中使用 $sort。我們建立一個包含文件的集合 -
> db.demo245.insertOne(
... {
... "_id": 101,
... "deatils": [
... { "DueDate": new ISODate("2019-01-10"), "Value": 45},
... {"DueDate": new ISODate("2019-11-10"), "Value": 34 }
... ]
... }
...);
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo245.insertOne(
... {
... "_id": 102,
... "details": [
... { "DueDate": new ISODate("2019-12-11"), "Value": 29},
... {"DueDate": new ISODate("2019-03-10"), "Value": 78}
... ]
... }
...);
{ "acknowledged" : true, "insertedId" : 102 }藉助 find() 方法顯示集合中的所有文件 -
> db.demo245.find();
這將產生以下輸出 -
{
"_id" : 101, "deatils" : [
{ "DueDate" : ISODate("2019-01-10T00:00:00Z"), "Value" : 45 },
{ "DueDate" : ISODate("2019-11-10T00:00:00Z"), "Value" : 34 }
]
}
{
"_id" : 102, "details" : [
{ "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 },
{ "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 } \
]
}以下是按子文件排序的查詢 -
> db.demo245.aggregate([
... { "$unwind": "$details" },
... { "$sort": { "_id": 1, "details.Value": -1 } },
... { "$group": {
... "_id": "$_id",
... "details": { "$push": "$details" }
... }},
... { "$sort": { "details.Value": -1 } }
...])這將產生以下輸出 -
{ "_id" : 102, "details" : [ { "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 }, { "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 } ] }
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP