如何在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" }
以上是 如何在MongoDB中进行字母数字排序? 的全部内容, 来源链接: utcz.com/z/347135.html