【问题标题】:The method aggregate(List<? extends Bson>) in the type MongoCollection<Document> is not applicable for the arguments (BasicDBObject)MongoCollection<Document> 类型中的方法 aggregate(List<? extends Bson>) 不适用于参数 (BasicDBObject)
【发布时间】:2017-10-04 13:07:21
【问题描述】:

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

MongoCollection 类型中的方法 aggregate(List) 不适用于参数 (BasicDBObject)

以下是我的代码 sn-p。提前致谢。

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;
}

【问题讨论】:

    标签: mongodb collections hashmap aggregation-framework mongodb-java


    【解决方案1】:

    在不知道您使用的是什么版本的 MongoDB Java 驱动程序的情况下回答这个问题有点棘手......

    自从在 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 类型中的方法 aggregate(List) 不适用于参数 (BasicDBObject)”

    ... 暗示您正在尝试调用 aggregate(List) 并将其分配给 AggregationOutput 让我怀疑您使用的是 v2.1x(请参阅 API docs。如果是这样,那么发布的示例在您的问题中可以重述如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多