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 发现:列表
我该如何解决这个问题?
答案 0 :(得分:0)
您正在将java驱动程序2.x api与3.x驱动程序API混合使用。
MongoCollection
,MongoDatabase
,Document
/ Bson
是3.x类,而DBCollection
,DB
和BasicDBObject
/ 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/