如何使用 mongodb java-driver Projections.slice

CXW*_*rks 2 java mongodb aggregation-framework

我正在尝试使用 Aggregates.project 对文档中的数组进行切片。我的文件就像

{
"date":"",
"stype_0":[1,2,3,4]
}
Run Code Online (Sandbox Code Playgroud)

在蒙戈切夫看起来像 该文件

我的java代码是:

Aggregates.project(Projections.fields(
                                Projections.slice("stype_0", pst-1, pen-pst),Projections.slice("stype_1", pst-1, pen-pst),
                                Projections.slice("stype_2", pst-1, pen-pst),Projections.slice("stype_3", pst-1, pen-pst))))
Run Code Online (Sandbox Code Playgroud)

最后我得到了错误

First argument to $slice must be an array, but is of type: int
Run Code Online (Sandbox Code Playgroud)

我想这是因为 stype_0 中的第一个元素是 int ,但我真的不知道为什么?多谢!

use*_*814 5

Slice 有两个版本。$slice(aggregation)$slice(projection)。你用错了。

聚合切片函数没有任何内置支持。以下是此类投影的一个示例。对所有其他投影场执行相同的操作。

List stype_0 = Arrays.asList("$stype_0", 1, 1);    
Bson project = Aggregates.project(Projections.fields(new Document("stype_0", new Document("$slice", stype_0))));
AggregateIterable<Document> iterable = dbCollection.aggregate(Arrays.asList(project));
Run Code Online (Sandbox Code Playgroud)