java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl não pode ser convertido em java.util.ArrayList

Sep 01 2020

Eu tenho o documento abaixo. Preciso fazer a correspondência com o Bob do sistema requestParam com a coleção abaixo e preciso obter o valor do resultado se requestParam corresponder ao Email Systems.Bob.System.

Aqui RequestParam é o sistema

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

Tentei com a sintaxe abaixo, obtendo java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl não pode ser convertido em java.util.ArrayList. Alguém pode me dizer o que há de errado com o código abaixo e me ajudar com a sintaxe.

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

Respostas

1 Milgo Sep 01 2020 at 15:17

O objeto retornado por users.aggregate () é um AggregateIterable. ArrayList não implementa essa interface, portanto, seu elenco falha. Tente lançar e trabalhar com ele como um AggregateIterable ou AggregateIterableImpl.

1 IssamEl-atif Sep 01 2020 at 15:49

users.aggregate()retorna um AggregateIterablee não um ArrayListdaí o erro. Você pode criar um Iteratorde AggregateIterablee adicionar documentos a um 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());
}

Consulte a agregação MongoDB com driver Java para obter respostas detalhadas por versão de driver