java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl не может быть преобразован в java.util.ArrayList

Sep 01 2020

У меня есть документ ниже. Мне нужно сопоставить requestParam System Bob с приведенной ниже коллекцией и получить значение результата, если requestParam совпадает с Email Systems.Bob.System.

Здесь RequestParam - это система

{ 
    "_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
            }
        }
    ]
}

Я пробовал использовать приведенный ниже синтаксис, получив исключение java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl нельзя преобразовать в java.util.ArrayList. Может ли кто-нибудь сказать мне, что не так с приведенным ниже кодом, и помочь мне с 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)))));

Ответы

1 Milgo Sep 01 2020 at 15:17

Объект, возвращаемый функцией users.aggregate (), является AggregateIterable. ArrayList не реализует этот интерфейс, поэтому приведение не выполняется. Попробуйте преобразовать его и работать с ним как с AggregateIterable или AggregateIterableImpl.

1 IssamEl-atif Sep 01 2020 at 15:49

users.aggregate()вернуть, AggregateIterableа не, ArrayListследовательно, ошибка. Вы можете создать Iteratorиз, AggregateIterableа затем добавить документы в 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());
}

Подробный ответ для каждой версии драйвера см. В разделе Агрегирование MongoDB с драйвером Java.