我需要为集合中的文档创建一个对象图。我可以获取所有键值对。以下是执行此操作的代码:
import com.mongodb.*;
import java.util.*;
public class GetKeyValuePair {
public static void print(DBObject doc) {
Set<String> allKeys = doc.keySet();
Iterator<String> 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<String> colls = db.getCollectionNames();
DBCollection coll = db.getCollection("first");
DBObject doc = new BasicDBObject();
DBCursor cur = coll.find();
Set<String> allKeys;
Iterator<String> 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);
}
}}
有没有其他更简单的方法可以做到这一点?谢谢提前。