使用组中最后一个聚合的mongodb java驱动程序

使用组中最后一个聚合的mongodb java驱动程序,java,mongodb,aggregation-framework,Java,Mongodb,Aggregation Framework,我的mongodb集合“事件”包括3个字段:编号、日期、类型。我想知道的是,有多少“事件”的编号为最近的日期(我的意思是,它们是该编号的最新事件),类型为3 我在mongo中的查询正在运行,但我不知道如何使用java驱动程序将其转换为java,因为我不了解累加器的参数。最后一个函数(并且找不到任何示例!)我知道我可以将其作为字符串编写,但我更喜欢使用mongodb java驱动程序API。在mongo中,查询是: db.events.aggregate([ {$sort:{date:1}}

我的mongodb集合“事件”包括3个字段:编号、日期、类型。我想知道的是,有多少“事件”的编号为最近的日期(我的意思是,它们是该编号的最新事件),类型为3

我在mongo中的查询正在运行,但我不知道如何使用java驱动程序将其转换为java,因为我不了解累加器的参数。最后一个函数(并且找不到任何示例!)我知道我可以将其作为字符串编写,但我更喜欢使用mongodb java驱动程序API。在mongo中,查询是:

db.events.aggregate([ 
  {$sort:{date:1}}, 
  {$group: {
    _id: {"number" : "$number"},
    "recent" : {$last: {action:"$$ROOT.type"}}
  }}, 
  {$match: {"recent.action" : 3}}, 
  {$count: "Qty"} 
],{allowDiskUse: true});
我想写的是:

Bson stage1 =  Aggregates.sort(Sorts.orderBy(Sorts.ascending("date")));
Bson stage2 = Aggregates.group("$number", Accumulators.last("recent", Accumulators.push("recentEvent", "$$ROOT")));
Bson deleteType = Filters.eq("recent.recentEvent.type", 3);
Bson stage3 = Aggregates.match(deleteType );
Bson stage4 = Aggregates.count("numberOfLastDelete");
pipeline = Arrays.asList(stage1, stage2, stage3, stage4);
result = collection.aggregate(pipeline).allowDiskUse(true).useCursor(true);
Document lastDeleteNumDoc = result.iterator().next();
这不起作用,最后一行出现错误:

org.bson.codecs.configuration.CodecConfigurationException:找不到com.mongodb.client.model.BsonField类的编解码器

如果我不为组使用API,则此代码正常工作:

    Bson stage1 =  Aggregates.sort(Sorts.ascending("date"));

    String groupString =
            "{" +
                "$group:" +
                "{" +
                    "_id: \"$number\", " +
                    "\"recent\": { $last: {lastType:\"$$ROOT.type\"} } " +
                "}" +
            "}";


    Bson stage2 = Document.parse(groupString);
    Bson deleteType = Filters.eq("recent.type",3);
    Bson stage3 = Aggregates.match(deleteType );
    Bson stage4 = Aggregates.count("numberOfLastDelete");
    pipeline = Arrays.asList(stage1, stage2, stage3, stage4);
    result = collection.aggregate(pipeline).allowDiskUse(true).useCursor(true);
    Document lastDeleteNumDoc = result.iterator().next();
    Integer lastDeleteNum = lastDeleteNumDoc.getInteger("numberOfLastDelete");
有什么想法吗? 谢谢
Osnat

显示您拥有的文档的小样本以及您期望从该样本中得到的结果。即使您的shell操作中也有各种看起来错误的东西,因此最好从头开始看整个问题。谢谢你的努力。对不起,我修好了外壳。此外,我还添加了在java中工作但不使用API的代码