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

드라이버 버전 별 자세한 답변은 Java 드라이버 를 사용한 MongoDB 집계를 참조하십시오.