2016-11-12 64 views
0

我想使用Aggregates.project切片我的文檔中的數組。 我的文檔就像如何使用mongodb的java驅動程序Projections.slice

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

看起來像 the document

和我的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)))) 

最後我得到錯誤

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

我猜這是因爲stype_0中的第一個元素是int,但我真的不知道爲什麼?非常感謝!

回答

2

切片有兩個版本。 $slice(aggregation) & $slice(projection)。你使用的是錯誤的。

聚合切片功能沒有任何內置支持。下面是一個這樣的預測的例子。對所有其他投影字段執行相同操作。

BasicDBList stype_0 = new BasicDBList(); 
    stype_0.add("$stype_0"); 
    stype_0.add(1); 
    stype_0.add(1); 

    Bson project = Aggregates.project(Projections.fields(new BasicDBObject("stype_0", new BasicDBObject("$slice", stype_0)))); 

    AggregateIterable<Document> iterable = dbCollection.aggregate(Arrays.asList(project)); 
+0

哦!我太粗心了,非常感謝你 – CXWorks