[英]Embedded Array Retrieval Mongodb Java
I've been trying to get this query, but I have been unable to roll my heads over this one. 我一直在尝试获取此查询,但是一直无法解决这个问题。
The Object looks like this: 对象看起来像这样:
{
restaurantName:'abc',
reviews:[
{
text:'Its awesome!'
person: 'John Doe'
}
{
text:'Nice Ambience'
person: 'Davis'
}
]
}
The intent is to find out all the reviews text present in the document. 目的是找出文档中存在的所有评论文本。 How do I do this using JAVA driver for Mongo.
如何使用Mongo的JAVA驱动程序执行此操作。 I keep getting Class Cast Exceptions
我不断收到Class Cast Exceptions
Following is the code: 以下是代码:
Set fields = new TreeSet(); 设置字段= new TreeSet();
BasicDBList e ;
try {
DBObject dbObject;
while (cursor.hasNext()) {
doc = new Document();
e = (BasicDBList) cursor.next().get("reviews");
for(BasicDBObject temp: e){
fields.addAll(temp.keySet());
}
}
//System.out.println(cursor.next());
}
The error I am getting is: 我得到的错误是:
Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to java.util.ArrayList at org.poly.darshan.utils.DataExtractor.main(DataExtractor.java:57)
The code mentioned above intends to find the unique fields present in the sub-objects. 上面提到的代码旨在查找子对象中存在的唯一字段。 But the problem is more or less the same.
但是问题或多或少都是一样的。
Ok found the Solution. 确定找到了解决方案。 In my case I know the field names, so I can retrieve the DBObject and then check for each field name and typecast it accordingly to retrieve it.
就我而言,我知道字段名称,因此我可以检索DBObject,然后检查每个字段名称并进行相应的类型转换以检索它。 *Wonders how free the wonderland of Javascript is.
*想知道Javascript的仙境有多自由。 Luckily in Java, we mostly always know what we are going to get.:)
幸运的是,在Java中,我们几乎总是知道我们将得到什么。
The solution looks something like this: 解决方案如下所示:
while (cursor.hasNext()) {
doc = new Document();
e = cursor.next();
for (String field : e.keySet()) {
if (field.equals("reviews")) {
BSONObject temp = (BSONObject) e.get(field);
System.out.println(temp.toString());
}
//else print the other String values
}
}
If BSOONList is retrieved, then typecast it accordingly. 如果检索到BSOONList,则进行相应的类型转换。 BSONList may contain BSONList or BSONObject, so it gets messy if you dont know what you want to retrieve.
BSONList可能包含BSONList或BSONObject,因此如果您不知道要检索的内容,它将变得混乱。 Dynamic Typecasting is helpful in these cases.
在这些情况下,动态类型转换非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.