Take the 2-minute tour ×

I have some problems to understand nosql. Im using mongodb and java and would like to create something like that: a table (persons) with a column for name (as string), age (as integer), married (boolean). In a normal sql it would be easy... but how to go on with mongodb and java?

Ok stuff I know: a table in mongodb is a collection and a column is a BSON field. I would start like this

        Mongo m = new Mongo();
        DB db = m.getDB("myDatabase");
        DBCollection col = db.getCollection("Persons");
        BasicDBObject doc = new BasicDBObject();
        doc.put("something?", "something?");

the first 3 steps are easy. I have my collection (table), I should make the BSON fields (columns) name, age, married. But how? I know the put() method, but what should I put in? And if I have the construct, I would like to add some "persons".

Any ideas? Thank you

share|improve this question
morphia or other Java POJO to Mongo Data base mapper will help too –  tgkprog Aug 25 '13 at 7:55
add comment

2 Answers

You should try to get rid of thinking about columns with MongoDB. It is schemaless so every document may have different set of fields even in same collection so thinking fields are columns may be misleading.

I recommend going through the official MongoDB Java tutorial HERE.

You should be able to do something like this:

doc.put("name", "John");
doc.put("age", 30);
doc.put("married", false);
share|improve this answer
add comment

Taking a look at the documentation here: http://api.mongodb.org/java/2.0/org/bson/BasicBSONObject.html#put(java.lang.String, java.lang.Object)

It seems to me that put accepts key and value for one of your fields, for instance:

doc.put("name", myPersonInstance.getName());
doc.put("age", myPersonInstance.getAge());

You can insert as many attributes using put as you want. There's also methods to add from a Map and such.

Please keep in mind I've never used the MongoDB Java API, so I'm basing my statements solely on that documentation and some slight knowledge of MongoDB in general.

For the record, those "put's" would be equivalent to a JSON structure like:

{name: "John", age:35}

Hope it helps.

share|improve this answer
add comment

Your Answer


