Getting a subdocument from mongo db using java Driver

I need to create an object graph for documents in a collection. I can get all key-value pairs. Here is the code that does this:

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 to do this, I mean a pretty simple way. thanks in advance

+3
source share
1 answer

If your use case allows, and existing Java ORM devices like Morphia don't work for you, you can use ReflectionDBObject. If you do not stick to your approach, there are no shortcuts.

0
source

Source: https://habr.com/ru/post/1788425/


All Articles