java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl không thể truyền sang java.util.ArrayList

Sep 01 2020

Tôi có tài liệu dưới đây. Tôi cần khớp với requestParam System Bob với tập hợp bên dưới và cần lấy giá trị kết quả nếu requestParam khớp với Email Systems.Bob.System.

Đây RequestParam là hệ thống

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

Tôi đã thử với cú pháp dưới đây, nhận được java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl không thể truyền sang java.util.ArrayList. Bất cứ ai có thể cho tôi biết điều gì bị lỗi với mã dưới đây và giúp tôi với 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)))));

Trả lời

1 Milgo Sep 01 2020 at 15:17

Đối tượng do users.aggregate () trả về là AggregateIterable. ArrayList không triển khai giao diện này nên quá trình truyền của bạn không thành công. Cố gắng truyền và làm việc với nó dưới dạng AggregateIterable hoặc AggregateIterableImpl.

1 IssamEl-atif Sep 01 2020 at 15:49

users.aggregate()trả về một AggregateIterablevà không phải là ArrayListlỗi do đó. Bạn có thể tạo một Iteratortừ AggregateIterablevà sau đó thêm tài liệu vào một 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());
}

Xem tổng hợp MongoDB với trình điều khiển Java để biết câu trả lời được tách ra cho mỗi phiên bản trình điều khiển