从 MongoDB 整理中获取不需要的输出

Vij*_*hit 5 java collation mongodb aggregation-framework mongo-java-driver

我正在尝试以“abc”的形式对发布版本进行排序

我正在使用 mongo-java-driver

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.8.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

我已经用排序规则创建了索引:

{
    "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"
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经使用 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);
Run Code Online (Sandbox Code Playgroud)

我将文档中的列表作为 API 响应返回。

return new Document("version", response);
Run Code Online (Sandbox Code Playgroud)

但我得到的输出是:

{ "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" }] }
Run Code Online (Sandbox Code Playgroud)

当我对 Mongo shell 进行相同尝试时,我得到以下输出(这是正确的)

{
  version:[
    {
    "version" : "1.10.1"
    },
    {
    "version" : "1.10.0"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我的 Java 代码有什么问题?是版本号还是代码错误?

任何帮助将非常感激。

Vij*_*hit 2

发现问题了

我调试了该问题,发现排序规则使用normalization来编码查询响应。默认情况下,该值为false。因此,shell 查询返回了正确的输出。

但在 Mongo-java-Driver 中它被设置normalizationtrue(默认情况下)。

使用标准化更新了构建器,如下false所示:

Collation collation = Collation.builder().locale("en").numericOrdering(true).normalization(false).build();
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)

这解决了我的问题。