java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl non può essere cast a java.util.ArrayList

Sep 01 2020

Ho sotto il documento. Devo abbinare il requestParam System Bob con la raccolta sottostante e devo ottenere il valore del risultato se requestParam corrisponde a Email Systems.Bob.System.

Qui RequestParam è il 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
            }
        }
    ]
}

Ho provato con la sintassi seguente, ottenendo java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl non può essere cast su java.util.ArrayList. Qualcuno può dirmi cosa c'è che non va nel codice seguente e aiutarmi con la sintassi.

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

Risposte

1 Milgo Sep 01 2020 at 15:17

L'oggetto restituito da users.aggregate () è un AggregateIterable. ArrayList non implementa questa interfaccia, quindi il cast non riesce. Prova a eseguire il cast e a utilizzarlo come AggregateIterable o AggregateIterableImpl.

1 IssamEl-atif Sep 01 2020 at 15:49

users.aggregate()restituisce an AggregateIterablee non an da ArrayListcui l'errore. È possibile creare un file Iteratorda AggregateIterablee quindi aggiungere documenti a un file 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());
}

Vedere Aggregazione MongoDB con driver Java per una risposta dettagliata per versione del driver