MongoDB中不区分大小写的排序
如何区分大小写不区分给定字段的MongoDB集合? 默认情况下,我在a-z之前得到A-Z。
我正在使用Java。
7个解决方案
42 votes
更新:截至目前,mongodb具有不区分大小写的索引:
Users.find({})
.collation({locale: "en" })
.sort({name: 1})
.exec()
.then(...)
贝壳:
db.getCollection('users')
.find({})
.collation({'locale':'en'})
.sort({'firstName':1})
更新:此答案已过期,3.4将具有不区分大小写的索引。 请查看JIRA以获取更多信息[https://jira.mongodb.org/browse/SERVER-90]
不幸的是,MongoDB尚没有不区分大小写的索引:[https://jira.mongodb.org/browse/SERVER-90]并且该任务已被推迟。
这意味着当前排序不区分大小写的唯一方法是实际创建一个特定的“小写”字段,然后复制所讨论的排序字段的值(当然是小写)并对其进行排序。
Sammaye answered 2020-01-28T21:01:35Z
41 votes
排序在MongoDB中的工作方式确实与之类似,但是您可以通过聚合即时执行此操作:
取得以下数据:
{ "field" : "BBB" }
{ "field" : "aaa" }
{ "field" : "AAA" }
因此,使用以下语句:
db.collection.aggregate([
{ "$project": {
"field": 1,
"insensitive": { "$toLower": "$field" }
}},
{ "$sort": { "insensitive": 1 } }
])
会产生如下结果:
{
"field" : "aaa",
"insensitive" : "aaa"
},
{
"field" : "AAA",
"insensitive" : "aaa"
},
{
"field" : "BBB",
"insensitive" : "bbb"
}
对于转换时会导致相同键的任何值,将保留实际的插入顺序。
Neil Lunn answered 2020-01-28T21:02:13Z
16 votes
在MongoDB JIRA上,这个问题已经存在很长时间了,但是现在已经解决了。 请查看此发行说明以获取详细文档。 您应该使用collation。
User.find()
.collation({locale: "en" }) //or whatever collation you want
.sort({name:'asc'})
.exec(function(err, users) {
// use your case insensitive sorted results
});
Mladen Janjetovic answered 2020-01-28T21:02:33Z
2 votes
截至目前(mongodb 4),您可以执行以下操作:
mongo shell:
db.getCollection('users')
.find({})
.collation({'locale':'en'})
.sort({'firstName':1});
猫鼬:
Users.find({})
.collation({locale: "en" })
.sort({name: 1})
.exec()
.then(...)
这是mongodb支持的语言和语言环境。
Wajahath answered 2020-01-28T21:03:06Z
1 votes
它在Java中。 我混合了无参数和BasicDBObject的第一个key-val变体,仅用于变体
DBCollection coll = db.getCollection("foo");
List pipe = new ArrayList();
DBObject prjflds = new BasicDBObject();
prjflds.put("field", 1);
prjflds.put("insensitive", new BasicDBObject("$toLower", "$field"));
DBObject project = new BasicDBObject();
project.put("$project", prjflds);
pipe.add(project);
DBObject sort = new BasicDBObject();
sort.put("$sort", new BasicDBObject("insensitive", 1));
pipe.add(sort);
AggregationOutput agg = coll.aggregate(pipe);
for (DBObject result : agg.results()) {
System.out.println(result);
}
Buzz Moschetti answered 2020-01-28T21:03:26Z
1 votes
添加代码.collation({'locale':'en'})帮助解决了我的问题。
Monu Chaudhary answered 2020-01-28T21:03:46Z
-2 votes
我们借助JavaScript数组中的.sort函数来解决此问题
这是代码
function foo() {
let results = collections.find({
_id: _id
}, {
fields: {
'username': 1,
}
}).fetch();
results.sort((a, b)=>{
var nameA = a.username.toUpperCase();
var nameB = b.username.toUpperCase();
if (nameA nameB) {
return 1;
}
return 0;
});
return results;
}
Kevin Alviola answered 2020-01-28T21:04:10Z