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

Sắp xếp mảng con (inner array) trong MongoDB

Dùng aggregation framework để sắp xếp mảng con. Tạo collection sortInnerArrayDemo với cấu trúc lồng sâu:

> db.sortInnerArrayDemo.insertOne({ "EmployeeDetails": { "EmployeeAddress": { "EmployeeCountry": [ {"EmployeeZipCode":1003,"EmployeeStreetName":"7885 Trusel Street"}, {"EmployeeZipCode":1001,"EmployeeStreetName":"7390 Gonzales Drive"}, {"EmployeeZipCode":1002,"EmployeeStreetName":"444 N.Myres Rd."} ] } } });
{ "acknowledged" : true, "insertedId" : ObjectId("5c6f07d3da34711ecf87a5b8") }

Hiển thị (thứ tự ban đầu: 1003, 1001, 1002):

> db.sortInnerArrayDemo.find().pretty();

Trường hợp 1: Sắp xếp tăng dần (ascending) theo EmployeeZipCode

> db.sortInnerArrayDemo.aggregate( {$unwind: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}, {$sort: {'EmployeeDetails.EmployeeAddress.EmployeeCountry.EmployeeZipCode': 1}}, {$group: {_id: '$_id', 'EmpCountry': {$push: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}}}, {$project: {'EmployeeDetails.EmployeeAddress.EmployeeCountry': '$EmpCountry'}}).pretty();

Kết quả: 1001, 1002, 1003.

Trường hợp 2: Sắp xếp giảm dần (descending)

> db.sortInnerArrayDemo.aggregate( {$unwind: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}, {$sort: {'EmployeeDetails.EmployeeAddress.EmployeeCountry.EmployeeZipCode': -1}}, {$group: {_id: '$_id', 'EmpCountry': {$push: '$EmployeeDetails.EmployeeAddress.EmployeeCountry'}}}, {$project: {'EmployeeDetails.EmployeeAddress.EmployeeCountry': '$EmpCountry'}}).pretty();

Kết quả: 1003, 1002, 1001.