我使用的是mongo-java-driver。
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.0</version>
</dependency>
我已经创建了带有整理的索引。
{
"v" : 2,
"key" : {
"version" : 1
},
"name" : "version_1",
"ns" : "db.sysversion",
"collation" : {
"locale" : "en",
"caseLevel" : false,
"caseFirst" : "off",
"strength" : 3,
"numericOrdering" : true,
"alternate" : "non-ignorable",
"maxVariable" : "punct",
"normalization" : false,
"backwards" : false,
"version" : "57.1"
}
}
我已经用java驱动实现了聚合查询。
Collation collation = Collation.builder().locale("en").numericOrdering(true).build();
ArrayList<Document> response = new ArrayList<>();
ArrayList<Bson> aggregate = new ArrayList<Bson>(Arrays.asList(
match(gt("version", "1.9.4")), sort(descending("version")),
project(fields(include("version"), exclude("_id")))
));
this.database.getCollection(sysversion).aggregate(aggregate).collation(collation).into(response);
我把列表以API响应的形式返回到一个文档中。
return new Document("version", response);
但我得到的输出是。
{ "version" : [{ "version" : "\u000f\u0003\b\u000f\f\b\u000f\u0003\u0001\t\u0001\t" }, { "version" : "\u000f\u0003\b\u000f\f\b\u000f\u0002\u0001\t\u0001\t" }] }
当我用Mongo shell尝试同样的方法时,我得到了以下的输出结果 (哪种说法正确)
{
version:[
{
"version" : "1.10.1"
},
{
"version" : "1.10.0"
}
]
}
我的Java代码怎么了,是版本的问题还是代码的错误?
任何帮助都将是非常感激的。
发现问题
笔者调试后发现,该问题的整理使用的是 normalization
用于对查询响应进行编码。默认情况下,该值是 false
. 所以,shell查询返回的是正确的输出。
但在Mongo-java-Driver中,它设置的是 normalization
作为 true
(默认情况下)。
更新了构建器,并将其标准化为 false
为相同的。
Collation collation = Collation.builder().locale("en").numericOrdering(true).normalization(false).build();
ArrayList<Document> response = new ArrayList<>();
ArrayList<Bson> aggregate = new ArrayList<Bson>(Arrays.asList(
match(gt("version", "1.9.4")), sort(descending("version")),
project(fields(include("version"), exclude("_id")))
));
this.database.getCollection(sysversion).aggregate(aggregate).collation(collation).into(response);
这解决了我的问题。