如何在 MongoDB 中进行字母数字排序?
要进行字母数字排序,您需要为 numericOrdering 设置:true。我们先使用文档创建集合 -
> 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") }
以下是使用 find() 方法显示集合中所有文档的查询 -
> db.alphanumericSortDemo.find().pretty();
这会产生以下输出 -
{ "_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" }
案例 1 - 当您希望结果按升序排列时。
以下是在 MongoDB 中进行字母数字排序的查询 -
> db.alphanumericSortDemo.find({}).sort({"StudentId" : 1}).collation( { locale: "en_US", numericOrdering: true });
这会产生以下输出 -
{ "_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" }
案例 2 - 当您希望结果按降序排列时。
以下是在 MongoDB 中进行字母数字排序的查询 -
> db.alphanumericSortDemo.find({}).sort({"StudentId" : -1}).collation( { locale: "en_US", numericOrdering: true });
这会产生以下输出 -
{ "_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" }
广告