MongoCollection <document>类型中的方法aggregate(List <! - ?extends Bson - >)不适用于参数(BasicDBObject)

时间:2017-10-04 13:07:22

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

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

  

MongoCollection类型中的方法聚合(List)不适用于参数(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;
}

1 个答案:

答案 0 :(得分:0)

在不知道您正在使用的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类型中的方法聚合(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")))
));