mongodb java中的不可转换类型错误?

时间:2017-03-21 18:41:25

标签: java mongodb aggregation-framework mongodb-java

 final DBObject group = new BasicDBObject("$group", groupFields);
 DBObject sort = new BasicDBObject("$sort", new BasicDBObject("NAME", -1));
 AggregateIterable <Document> aggregate = collection.aggregate((List<? extends Bson>) asList(group,sort));

该代码抛出此错误:

  

无法解析错误消息:required:List   发现:列表

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您正在将java驱动程序2.x api与3.x驱动程序API混合使用。

MongoCollectionMongoDatabaseDocument / Bson是3.x类,而DBCollectionDBBasicDBObject / DBObject是2.x类。

看起来你正在使用3.x驱动程序,所以你要做类似下面的事情。

 MongoClient mongoClient = new MongoClient();
 MongoDatabase db = mongoClient.getDatabase("db");
 MongoCollection<Document> collection = db.getCollection("collection");

 BsonField id = Accumulators.first("ID", "$ID");
 BsonField name = Accumulators.first("NAME", "NAME");
 BsonField amount = Accumulators.sum("amount", "$amount");

 Bson group = Aggregates.group("$NAME", id, name, amount);
 Bson sort = Aggregates.sort(Sorts.descending("NAME"));

 List<Document> results = collection.aggregate(Arrays.asList(group, sort)).into(new ArrayList<>());

此处提供更多信息http://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/