Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Sắp xếp theo subdocument trong MongoDB

Để sắp xếp theo subdocument, sử dụng $sort trong aggregation pipeline.

Tạo collection với mảng details chứa DueDate và Value:

> db.demo245.insertOne({
...   "_id": 101,
...   "details": [
...     { "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 }

Hiển thị dữ liệu gốc:

> db.demo245.find();
{ "_id" : 101, "details" : [
  { "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 }
] }

Pipeline: $unwind mảng, $sort theo _id tăng và Value giảm, $group gom lại mảng, $sort cuối theo Value giảm:

> db.demo245.aggregate([
...   { "$unwind": "$details" },
...   { "$sort": { "_id": 1, "details.Value": -1 } },
...   { "$group": {
...     "_id": "$_id",
...     "details": { "$push": "$details" }
...   }},
...   { "$sort": { "details.Value": -1 } }
...])

Kết quả: tài liệu 102 lên đầu (có Value=78 lớn nhất), mảng details đã sắp xếp Value giảm:

{ "_id" : 102, "details" : [
  { "DueDate" : ISODate("2019-03-10T00:00:00Z"), "Value" : 78 },
  { "DueDate" : ISODate("2019-12-11T00:00:00Z"), "Value" : 29 }
] }