我需要为集合中的文档创建一个对象图。
我能够获得所有的键值对。下面是这样做的代码:
import com.mongodb.*;
import java.util.*;
public class GetKeyValuePair {
public static void print(DBObject doc) {
Set allKeys = doc.keySet();
Iterator it = allKeys.iterator();
while (it.hasNext()) {
String temp = it.next();
System.out.print(temp + "-");
if (doc.get(temp) instanceof BasicDBObject) {
System.out.println("\n");
print((DBObject) doc.get(temp));
} else {
System.out.println(doc.get(temp));
}
}
}
public static void main(String args[]) {
try {
Mongo m = new Mongo();
DB db = m.getDB("test");
Set colls = db.getCollectionNames();
DBCollection coll = db.getCollection("first");
DBObject doc = new BasicDBObject();
DBCursor cur = coll.find();
Set allKeys;
Iterator it;
while (cur.hasNext()) {
doc = cur.next();
allKeys = doc.keySet();
it = allKeys.iterator();
print(doc);
System.out.println("-------");
}
} catch (UnknownHostException e) {
System.out.println(e.toString());
} catch (MongoException.DuplicateKey e) {
System.out.println("Exception Caught" + e);
}
}}有没有其他办法可以做到这一点,我的意思是一个相当简单的方法。
提前致谢