java.lang.ClassCastException: com.mongodb.client.internal.AggregateIterableImpl ไม่สามารถส่งไปยัง java.util.ArrayList
ฉันมีเอกสารด้านล่าง ฉันต้องการจับคู่กับ requestParam System Bob กับคอลเล็กชันด้านล่างและจำเป็นต้องได้รับค่าผลลัพธ์หาก requestParam ตรงกับระบบอีเมล 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)))));
คำตอบ
อ็อบเจ็กต์ที่ส่งคืนโดย users.aggregate () เป็น AggregateIterable ArrayList ไม่ใช้อินเทอร์เฟซนี้ดังนั้นการแคสของคุณจึงล้มเหลว พยายามแคสต์และใช้งานเป็น AggregateIterable หรือ AggregateIterableImpl
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สำหรับคำตอบโดยละเอียดตามเวอร์ชันของไดรเวอร์