3 回答
TA贡献1863条经验 获得超2个赞
就像您评论的那样,在您的代码中,您无法将 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);
}
我希望这对你有帮助。
TA贡献1851条经验 获得超5个赞
感谢所有的答案,这是我的最终代码:
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) {
Document dboNested = Document.class.cast(dboNestedObj);
if (dboNestedObj instanceof Document) {
keysNested.addAll(dboNested.keySet());
}
}
// else if extra...
} else if (value instanceof Document) {
Document dboNested = Document.class.cast(value);
keysNested.addAll(dboNested.keySet());
}
}
System.out.println("KeysNested: " + keysNested);
给定示例的输出:[property1, property2, property3, property4, ispropert5, ispropert6]
TA贡献1951条经验 获得超3个赞
我想我来晚了,但我正在尝试一种更 mongo 的方式来做到这一点。您肯定希望在一小部分查询上执行此操作,match甚至可能是开始此操作之前的一个阶段
db.coll.aggregate([{
$unwind: '$config'
}, {
$project: {
arr: {
$objectToArray: '$config'
}
}
}, {
$unwind: '$arr'
}, {
$group: {
_id: {
key: '$arr.k'
}
}
}, {
$project: {
key: '$_id.key',
_id: 0
}
}
])
添加回答
举报