这是我的MongoDB文档的简化架构:
{
"_id": 0,
"config": [{
"property1": "a",
"property2": "b",
"property3": "c",
"property4": "d"
},
{
"property1": "a",
"property2": "bb",
"property3": "cc",
"property4": "d",
"ispropert5": true
},
{
"property1": "a",
"property2": "b",
"property3": "c",
"property4": "ddd",
"ispropert5": false,
"ispropert6": false
}
],
"entity": "123asdf",
"url": "",
"createdDate": 1
}
作为输出,我需要获取嵌套文档的唯一键的列表:{property1,property2,property3,property4,ispropert5,ispropert6}
我在课堂上尝试这样做,但是当然无法将ArrayList转换为Document:
Document dbo = col.find().first();
Set<String> keys = dbo.keySet();
Iterator iterator = keys.iterator();
while(iterator.hasNext()) {
String key = iterator.next().toString();
if(dbo.get(key) instanceof ArrayList){
Document dboNested = (Document) dbo.get(key); //java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.bson.Document
Set<String> keysNested = dboNested.keySet();
System.out.println("KeyNested: " + keysNested);
}
}
就像您评论过的那样,您无法在代码上将ArrayList转换为Document,因此必须将其转换为如下所示的ArrayList:
while(iterator.hasNext()) {
String key = iterator.next().toString();
Object value = dbo.get(key);
if (value instanceof ArrayList){
ArrayList<?> dboArrayNested = (ArrayList<?>) value;
for (Object dboNestedObj : dboArrayNested) {
if (dboNestedObj instanceof Document) {
printKeysNested(Document.class.cast(dboNestedObj));
}
}
// else if extra...
} else if (value instanceof Document) {
printKeysNested(Document.class.cast(value));
}
}
public static void printKeysNested(Document dboNested) {
Set<String> keysNested = dboNested.keySet();
System.out.println("KeyNested: " + keysNested);
}
我希望这可以帮助你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句