java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl cannot be cast to java.util.ArrayList

Viewed 3763

I have got below document . I need to match with the requestParam System Bob with the below collection and need to get the result value if requestParam matches with the Email Systems.Bob.System.

Here RequestParam is system

{ 
    "_id" : ObjectId("5f0890e870e631865877e"), 
    "user" : "testuser", 
    "Email" : "testuser@sample.com", 
    "Batch Systems" : [
        "STAR", 
        "STORY", 
        "ITEMS",    
    ], 
    "Email Systems" : [
        {
            "Bob" : {
                "System" : "Bob", 
                **"result"** : true
            }
        }, 
        {
            "Wild" : {
                "System" : "Wild", 
                "result" : true
            }
        },
        {
            "CRaft" : {
                "System" : "Craft", 
                "result" : false
            }
        }
    ]
}

I have tried with the below syntax , getting the java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl cannot be cast to java.util.ArrayList . Can anyone tell me what is wrong with the below code and help me with the synatx .

MongoDatabase database = this.mongoClient.getDatabase(this.database);
    MongoCollection<Document> user = database.getCollection(COLLECTION);
    Document userQuery = new Document();
    String searchString = new String(system);
    AggregateIterable<Document> user1 =users.aggregate((List<? extends Bson>) new Document("$project",
                new Document("Email Systems",
                        new Document("$match",
                                new Document("Email  Systems.BobSystem",searchString)))));
2 Answers

The object returned by users.aggregate() is an AggregateIterable. ArrayList does not implement this interface so your cast fails. Try to cast and work with it as an AggregateIterable or AggregateIterableImpl.

users.aggregate() return an AggregateIterable and not an ArrayList hence the error. You can create an Iterator from AggregateIterable and then add documents to an ArrayList.

MongoDatabase database = this.mongoClient.getDatabase(this.database);
MongoCollection<Document> user = database.getCollection(COLLECTION);
Document userQuery = new Document();
String searchString = new String(system);
AggregateIterable aggregateIterable = users.aggregate(Collections.singletonList(new Document("$project", new Document("Email Systems", new Document("$match", new Document("Email Systems.Bob.System", searchString))))));
// Create an iterator from the iterable
Iterator iterator = aggregateIterable.iterator();
ArrayList<Document> documents = new ArrayList();
// Then iterate over the iterator
while (iterator.hasNext()) {
    documents.add((Document) iterator.next());
}

See MongoDB aggregation with Java driver for detailled answer per driver version

Related