3

I am fairly new to MongoDB / JSON so this might be very simple but I can't find a satisfactory answer.

Let's say I have 2 classes defined below (in reality much more complex):

public class Instrument {
    public String name;
    public List<Identifier> identifiers;
}

public class Identifier {
    public String type;
    public String value;
}

So one Instrument can have several Identifiers. Now I have a List<Instrument> that I would like to store in a Mongo collection called "instruments".
The only way I have found so far is to create each document manually by inserting their fields one by one (see the getDocFromInstrument method in the full working example below). This is very cumbersome and error prone + completely coupled with the underlying classes.

Is there a better way to do that?
And as I will need to get the information back at some stage, any ideas on how to "automatically" recreate the objects from the database is welcome too.

For information, the output of the code below is:

{ "_id" : { "$oid" : "4f44db111d8bc98c289b5d82"} , "name" : "inst1" , "identifiers" : [ { "type" : "type1" , "value" : "inst1_type1"} , { "type" : "type2" , "value" : "inst1_type2"}]}
{ "_id" : { "$oid" : "4f44db111d8bc98c289b5d83"} , "name" : "inst2" , "identifiers" : [ { "type" : "type1" , "value" : "inst2_type1"} , { "type" : "type2" , "value" : "inst2_type2"}]}

Full code:

public class TestMongo {

    private final static String IP = "192.168.3.12";
    private final static String DB_NAME = "test";
    private final static int DEFAULT_PORT = 27017;

    public static void main(String[] args) {
        DB db = null;
        try {
            db = new Mongo(IP, DEFAULT_PORT).getDB(DB_NAME);
            insertSomething(db);
            printContent(db);
            cleanDb(db);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (db != null) {
                db.getMongo().close();
            }
        }
    }

    private static void insertSomething(DB db) {
        Identifier idInst1_1 = new Identifier("type1", "inst1_type1");
        Identifier idInst1_2 = new Identifier("type2", "inst1_type2");
        Identifier idInst2_1 = new Identifier("type1", "inst2_type1");
        Identifier idInst2_2 = new Identifier("type2", "inst2_type2");

        Instrument inst1 = new Instrument("inst1", Arrays.asList(idInst1_1, idInst1_2));
        Instrument inst2 = new Instrument("inst2", Arrays.asList(idInst2_1, idInst2_2));

        BasicDBObject doc1 = getDocFromInstrument(inst1);
        BasicDBObject doc2 = getDocFromInstrument(inst2);

        DBCollection instrumentsCollection = db.getCollection("instruments");
        instrumentsCollection.insert(doc1);
        instrumentsCollection.insert(doc2);
    }

    private static void printContent(DB db) {
        DBCollection instrumentsCollection = db.getCollection("instruments");
        DBCursor cur = instrumentsCollection.find();

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }
    }

    private static void cleanDb(DB db) {
        db.dropDatabase();
    }

    private static BasicDBObject getDocFromInstrument(Instrument instrument) {
    BasicDBObject instrumentDoc = new BasicDBObject();
    instrumentDoc.put("name", instrument.name);
    List<BasicDBObject> identifiers = new ArrayList<>();
    for (Identifier identifier : instrument.identifiers) {
        BasicDBObject identifierDoc = new BasicDBObject();
        identifierDoc.put("type", identifier.type);
        identifierDoc.put("value", identifier.value);
        identifiers.add(identifierDoc);
    }
    instrumentDoc.put("identifiers", identifiers);
        return instrumentDoc;
    }

    static class Instrument {
        public String name;
        public List<Identifier> identifiers;

        public Instrument(String name, List<Identifier> ids) {
            this.name = name;
            this.identifiers = ids;
        }

    }

    static class Identifier {
        public String type = "";
        public String value = "";

        public Identifier(String type, String values) {
            this.type = type;
            this.value = values;
        }

    }
}

4 Answers 4

3

Take a look at Morphia, it's the Java ORM for MongoDB:

Morphia - Java ORM to/from MongoDB

I use it for my Java code and my classes look very similar to yours. I have not had any trouble nesting lists of objects within other objects. Morphia uses reflection to convert your classes into JSON, so it'll handle a lot of your code for you (such as your getDocFromInstrument function). Hope that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

I have tried it and it seems to do exactly what I needed. Thanks for the link.
3

There are several ORM tools you can try.But Morphia is the most stable one among them.

Comments

1

https://github.com/impetus-opensource/Kundera/wiki/Kundera-Mongo-performance

This a compiled performance comparision b/w Kundera, Spring Data, Morphia and Native API.

This should give you an idea which one is better. Kundera is providing client extension framework(a way to handle other mongodb requirements).

Comments

0

There is a list of Java POJO mappers on mongo's website.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.