我正在尝试以“a.b.c”的形式对发布版本进行排序
我正在使用 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);
这解决了我的问题。
关于java - 从 MongoDB 整理中获取不需要的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61591841/