SQL table for nosql (MongoDB) - simple example

I have some problems to understand nosql. I use mongodb and java and would like to create something like this: a table (persons) with a column for the name (as a row), age (as a whole), married (boolean). In regular sql, this would be easy ... but how to proceed with mongodb and java?

Ok, 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?"); col.insert(doc); 

The first 3 steps are simple. I have my collection (table), I must indicate the names (columns) of BSON, age, marriage. But how? I know the put () method, but what should I insert? And if I have a design, I would like to add a few "faces".

Any ideas? Thanks you

+7
source share
2 answers

You should try to get rid of column thinking with MongoDB. This is schematic, so each document can have a different set of fields even in the same collection, so columns can be confusing fields of thinking.

I recommend going through the official MongoDB Java tutorial HERE .

You should do something like this:

 doc.put("name", "John"); doc.put("age", 30); doc.put("married", false); 
+5
source

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 takes a key and a value for one of your fields, for example:

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

You can insert as many attributes as you want. There are also ways to add from a map, etc.

Please keep in mind that I have never used the MongoDB Java interface, so I base my statements solely on this documentation and some small knowledge of MongoDB in general.

For the record, these "put's" will be equivalent to a JSON structure, for example:

 {name: "John", age:35} 

Hope this helps.

+3
source

All Articles