Để sắp xếp theo tổng hai trường, bạn có thể sử dụng khung tổng hợp. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
> db.orderByTwoFieldsDemo.insertOne({"Value1":10,"Value2":35});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca285576304881c5ce84baa")
}
> db.orderByTwoFieldsDemo.insertOne({"Value1":12,"Value2":5});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca2855f6304881c5ce84bab")
}
> db.orderByTwoFieldsDemo.insertOne({"Value1":55,"Value2":65});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca285686304881c5ce84bac")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.orderByTwoFieldsDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5ca285576304881c5ce84baa"),
"Value1" : 10,
"Value2" : 35
}
{
"_id" : ObjectId("5ca2855f6304881c5ce84bab"),
"Value1" : 12,
"Value2" : 5
}
{
"_id" : ObjectId("5ca285686304881c5ce84bac"),
"Value1" : 55,
"Value2" : 65
} Trường hợp 1 :Sau đây là truy vấn để sắp xếp theo tổng hai trường và nhận kết quả theo thứ tự tăng dần:
> db.orderByTwoFieldsDemo.aggregate(
... [
... {$project:{Value1:1, Value2:1, orderBySumValue:{$add: ["$Value1", "$Value2"]}}},
... {$sort:{orderBySumValue:1}}]
... ); Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5ca2855f6304881c5ce84bab"), "Value1" : 12, "Value2" : 5,
"orderBySumValue" : 17 }
{ "_id" : ObjectId("5ca285576304881c5ce84baa"), "Value1" : 10, "Value2" : 35,
"orderBySumValue" : 45 }
{ "_id" : ObjectId("5ca285686304881c5ce84bac"), "Value1" : 55, "Value2" : 65,
"orderBySumValue" : 120 } Trường hợp 2 :Sau đây là truy vấn sắp xếp theo tổng hai trường và lấy kết quả theo thứ tự giảm dần
> db.orderByTwoFieldsDemo.aggregate( [ {$project:{Value1:1, Value2:1,
orderBySumValue:{$add: ["$Value1", "$Value2"]}}}, {$sort:{orderBySumValue:-1}}] ); Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5ca285686304881c5ce84bac"), "Value1" : 55, "Value2" : 65,
"orderBySumValue" : 120 }
{ "_id" : ObjectId("5ca285576304881c5ce84baa"), "Value1" : 10, "Value2" : 35,
"orderBySumValue" : 45 }
{ "_id" : ObjectId("5ca2855f6304881c5ce84bab"), "Value1" : 12, "Value2" : 5,
"orderBySumValue" : 17 }