Getting nested Document from mongo db using java Driver

2.1k views Asked by At

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

1

There are 1 answers

0
Remon van Vliet On

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.