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

Sắp xếp alphanumeric (số chữ kết hợp) trong MongoDB?

Cần set numericOrdering: true trong collation. Tạo collection:

> 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") }

Hiển thị tất cả:

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

Trường hợp 1: Tăng dần (ascending)

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

Kết quả (STU101, STU908, STU1010, STU1101, STU1901):

Trường hợp 2: Giảm dần (descending)

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

Kết quả ngược lại.