本文介绍了如何使用mongodb java-driver Projections.slice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use Aggregates.project to slice the array in my documents.My documents is like

{
"date":"",
"stype_0":[1,2,3,4]
}

在mongochef中看起来像

in the mongochef looks like

我在Java中的代码是:

and my code in java is :

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))))

最后我得到了错误

First argument to $slice must be an array, but is of type: int

我猜这是因为stype_0中的第一个元素是int,但我真的不知道为什么吗?非常感谢!

I guess that is because the first element in stype_0 is int , but I really do not know why? Thanks a lot!

推荐答案

Slice有两个版本. $slice(aggregation) & $slice(projection) .您使用的是错误的.

Slice has two versions. $slice(aggregation) & $slice(projection). You are using the wrong one.

聚合切片功能不具有任何内置支持.下面是一个这样的投影的例子.对所有其他投影字段执行相同的操作.

Aggregate slice function doesn't have any built-in support. Below is an example for one such projection. Do the same for all the other projection fields.

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));

这篇关于如何使用mongodb java-driver Projections.slice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 14:52