简体   繁体   中英

Getting nested Document from mongo db using java Driver

I need to create an Object graph for the documents in a collection. I am able to get all the key-value pairs. Here is the code which does that:

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);
    }
   }}

Is there any other way I can do this, I mean a rather simple way. Thanks in advance

If your use case allows it and existing Java ORM mappers such as Morphia don't work for you you can use ReflectionDBObject. If not you're stuck with your approach, there are no shortcuts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM