java.lang.ClassCastException:com.mongodb.client.internal.AggregateIterableImplをjava.util.ArrayListにキャストできません
Sep 01 2020
以下のドキュメントがあります。以下のコレクションでrequestParamSystem Bobと一致する必要があり、requestParamがEmailSystems.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ます。IteratorfromAggregateIterableを作成してから、にドキュメントを追加できます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集約を参照してください。