The method aggregate(List<? extends Bson>) in the type MongoCollection<Document> is not applicable for the arguments (BasicDBObject)

Viewed 1605

I am new to MongoDB. I am getting an error in loginCollection.aggregate stating:

The method aggregate(List) in the type MongoCollection is not applicable for the arguments (BasicDBObject)

Following is my code snippet. Thanks in advance.

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 Answers

It's a little bit tricky to answer this without knowing what version of the MongoDB Java driver you are using however...

Since sometime in the 2.x train the aggregate() method has accepted a List. For example:

// in 2.14
AggregationOutput aggregate(List<DBObject> pipeline)

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

The one and only argument is a List, this list represents the stages in an aggregation pipeline. For example:

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

The exception message included in your question:

"The method aggregate(List) in the type MongoCollection is not applicable for the arguments (BasicDBObject)"

... implies that you are attempting to call aggregate(List) and the assignment of that to a AggregationOutput makes me suspect that you are using v2.1x (see the API docs. If so, then the example posted in your question could be restated as follows:

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