Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để sắp xếp chữ và số trong MongoDB?

Bạn cần đặt số thứ tự:true cho sắp xếp chữ và số. 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.alphanumericSortDemo.insertOne({"StudentId":"STU1010"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf149adceb9a92e6aa194c")
}
> db.alphanumericSortDemo.insertOne({"StudentId":"STU1101"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf14a2dceb9a92e6aa194d")
}
> db.alphanumericSortDemo.insertOne({"StudentId":"STU1901"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf14a9dceb9a92e6aa194e")
}
> db.alphanumericSortDemo.insertOne({"StudentId":"STU908"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf14aedceb9a92e6aa194f")
}
> db.alphanumericSortDemo.insertOne({"StudentId":"STU101"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf14b2dceb9a92e6aa1950")
}

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.alphanumericSortDemo.find().pretty();

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5ccf149adceb9a92e6aa194c"), "StudentId" : "STU1010" }
{ "_id" : ObjectId("5ccf14a2dceb9a92e6aa194d"), "StudentId" : "STU1101" }
{ "_id" : ObjectId("5ccf14a9dceb9a92e6aa194e"), "StudentId" : "STU1901" }
{ "_id" : ObjectId("5ccf14aedceb9a92e6aa194f"), "StudentId" : "STU908" }
{ "_id" : ObjectId("5ccf14b2dceb9a92e6aa1950"), "StudentId" : "STU101" }

Trường hợp 1 - Khi bạn muốn kết quả theo thứ tự tăng dần.

Đây là truy vấn để thực hiện sắp xếp chữ và số trong MongoDB -

> db.alphanumericSortDemo.find({}).sort({"StudentId" : 1}).collation( { locale: "en_US", numericOrdering: true });

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5ccf14b2dceb9a92e6aa1950"), "StudentId" : "STU101" }
{ "_id" : ObjectId("5ccf14aedceb9a92e6aa194f"), "StudentId" : "STU908" }
{ "_id" : ObjectId("5ccf149adceb9a92e6aa194c"), "StudentId" : "STU1010" }
{ "_id" : ObjectId("5ccf14a2dceb9a92e6aa194d"), "StudentId" : "STU1101" }
{ "_id" : ObjectId("5ccf14a9dceb9a92e6aa194e"), "StudentId" : "STU1901" }

Trường hợp 2 - Khi bạn muốn kết quả theo thứ tự giảm dần.

Đây là truy vấn để thực hiện sắp xếp chữ và số trong MongoDB -

> db.alphanumericSortDemo.find({}).sort({"StudentId" : -1}).collation( { locale: "en_US", numericOrdering: true });

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5ccf14a9dceb9a92e6aa194e"), "StudentId" : "STU1901" }
{ "_id" : ObjectId("5ccf14a2dceb9a92e6aa194d"), "StudentId" : "STU1101" }
{ "_id" : ObjectId("5ccf149adceb9a92e6aa194c"), "StudentId" : "STU1010" }
{ "_id" : ObjectId("5ccf14aedceb9a92e6aa194f"), "StudentId" : "STU908" }
{ "_id" : ObjectId("5ccf14b2dceb9a92e6aa1950"), "StudentId" : "STU101" }