使用聚合对java代码进行MongoDb查询

使用聚合对java代码进行MongoDb查询,java,mongodb,aggregation-framework,Java,Mongodb,Aggregation Framework,有人能帮我把下面的查询转换成java代码吗 我已经用java编写了以下查询,如下所示,但出现以下错误 命令失败,错误为168:'服务器上无法识别的表达式'$push'。完整响应为{“ok”:0.0,“errmsg”:“无法识别的表达式'$push'”,“代码”:168,“代码名”:“InvalidPipelineOperator”} 查询: db.getCollection('xyz').aggregate([ {$match: { "_id":{$in: [{"a"

有人能帮我把下面的查询转换成java代码吗

我已经用java编写了以下查询,如下所示,但出现以下错误

命令失败,错误为168:'服务器上无法识别的表达式'$push'。完整响应为{“ok”:0.0,“errmsg”:“无法识别的表达式'$push'”,“代码”:168,“代码名”:“InvalidPipelineOperator”}

查询:

db.getCollection('xyz').aggregate([
             {$match: { "_id":{$in: [{"a" : "NA","b" : "HXYZ","c" : "12345","d" : "CA"}]}
                     }
                   },
              { $unwind: '$bal' },
              {
                 $sort: {'bal.date': -1}
              },
              {$group:
                   {"_id": "$_id",bal:{$push:'$bal'}}},
               { $project: {
            balances: { $slice: ["$bal",2]} 
                            }
               }

       ])
Java代码:

List<Document> findDocument=collectionName.aggregate(
            Arrays.asList(
                Aggregates.match(in("_id",tempList)),
            Aggregates.unwind("$bal"),
            Aggregates.sort(Sorts.descending("bal.date")),
            Aggregates.group(new Document("_id","$_id").append("bal",new Document("$push","$bal"))),
        Aggregates.project(new Document("bal",new Document ("$slice",Arrays.asList("$bal", 2)))))).into(new ArrayList<Document>());
List findDocument=collectionName.aggregate(
Arrays.asList(
Aggregates.match(在(“_id”,templast))中,
集合。展开($bal),
聚合.排序(排序.降序(“余额日期”),
聚合.group(新文档(“\u id”,“$\u id”).append(“bal”,新文档(“$push”,“$bal”)),
聚合.project(新文档(“bal”,新文档(“$slice”,Arrays.asList(“$bal”,2‘‘‘‘‘‘)’)。到(新的ArrayList());
Mongo DB的版本是3.4。 有人能告诉我为什么$push不起作用吗?
提前感谢。

您将文档推送到id字段,而不是单独创建推送文档

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.in;
import static com.mongodb.client.model.Sorts.*;
import static java.util.Arrays.*;
List<Document> results = collectionName.aggregate(
     asList(
          match(in("_id",tempList)),
          unwind("$bal"),
          sort(descending("bal.date")),
          group("$_id", push("bal","$bal")),
          project(new Document("bal",new Document ("$slice", asList("$bal", 2))))
    )
).into(new ArrayList<>());
导入静态com.mongodb.client.model.累加器。*;
导入静态com.mongodb.client.model.Aggregates.*;
导入静态com.mongodb.client.model.Filters.in;
导入静态com.mongodb.client.model.Sorts.*;
导入静态java.util.Arrays.*;
列表结果=collectionName.aggregate(
asList(
匹配(在(“_id”,templast)),
展开($bal),
排序(降序(“余额日期”),
组($_id),推送(“bal”,即“$bal”),
项目(新文档(“bal”,新文档($slice),asList($bal,2)))
)
).into(新数组列表());