MongoCollection 类型中的方法 aggregate(List<? extend Bson>) 不适用于<Document>参数 (BasicDBObject)



我是MongoDB的新手。我在loginCollection.aggregate中遇到错误:

类型Mongocollection中的方法汇总(列表)不适用于参数(BasicDBobject)

以下是我的代码段。预先感谢。

public MonthlyLoginCount monthlyLoginCount() {
    MonthlyLoginCount monthlyLoginCount = new MonthlyLoginCount();
    Map<String, Long> map = new HashMap<String, Long>();
    MongoClient mongo = new MongoClient(dataSource, 27017);
    MongoCollection<Document> loginCollection = mongo.getDatabase(mongoDataBase).getCollection(loginDetailsCollection);
    AggregationOutput logincount = loginCollection.aggregate(new BasicDBObject("$group",
            new BasicDBObject("_id", "$email_id").append("value", new BasicDBObject("$push", "$value"))));
    Iterator<DBObject> results = logincount.results().iterator();
    while (results.hasNext()) {
        try {
            Object str = results.next().get("_id");
            long count = loginCollection.count(new BasicDBObject("email_id", str.toString()));
            System.out.println("email id:: " + str.toString() + " count: " + count);
            map.put(str.toString(), count);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    mongo.close();
    monthlyLoginCount.setMap(map);
    return monthlyLoginCount;
}

回答此问题有点棘手

自2.x火车中的某个时候,aggregate()方法已接受List。例如:

// in 2.14
AggregationOutput aggregate(List<DBObject> pipeline)
// in 3.x
AggregateIterable<TDocument> aggregate(List<? extends Bson> pipeline);

唯一的参数是List,此列表表示聚合管道中的阶段。例如:

AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
        new Document("$match", theMatchDocument),
        new Document("$project", theProjectionDocument)
));

您的问题中包含的异常消息:

"类型Mongocollection中的方法汇总(列表)不适用于参数(BasicDBobject)"

...意味着您正在尝试致电aggregate(List),并且将其分配给AggregationOutput使我怀疑您正在使用v2.1x(请参阅API文档。重述如下:

AggregationOutput logincount = loginCollection.aggregate(Arrays.asList(
        new BasicDBObject("$group", new BasicDBObject("_id", "$email_id").append("value", new BasicDBObject("$push", "$value")))
));

最新更新