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

Cách đơn giản nhất để sắp xếp mảng trong MongoDB

Cách dễ nhất để sắp xếp mảng trong MongoDB là sử dụng $sort trong aggregation pipeline. Tạo collection với mảng lồng nhau:

> db.demo242.insertOne({
...   "details2": [
...     {"ShipingDate":new ISODate("2019-10-11"),"Price":1400},
...     {"ShipingDate":new ISODate("2019-10-01"),"Price":1600}
...   ]
...});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4429229af932883c61ea44") }

Hiển thị dữ liệu gốc (mảng chưa sắp xếp):

> db.demo242.find();
{ "_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [
  { "ShipingDate" : ISODate("2019-10-11T00:00:00Z"), "Price" : 1400 },
  { "ShipingDate" : ISODate("2019-10-01T00:00:00Z"), "Price" : 1600 }
] }

Pipeline sắp xếp mảng theo ShipingDate tăng dần:

> db.demo242.aggregate([
  {$unwind: "$details2"},
  {$sort: {"details2.ShipingDate":1}},
  {$group: {_id:"$_id", details2: {$push:"$details2.ShipingDate"}}}
]);

Kết quả mảng đã được sắp xếp theo ngày:

{ "_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [
  ISODate("2019-10-01T00:00:00Z"),
  ISODate("2019-10-11T00:00:00Z")
] }