Search code examples
javamongodb

mongodb and java driver rebuild objects


I'm trying to understand how mongodb works and I have some questions.

I understand how to delete, insert, update and select but I have some "best practice questions"

  1. Did we have to create an index or we can just use the _id which is auto generated?

  2. If I have for example 2 kind of objects (cars and drivers) with a n-n relation between. I have to get 3 collections(car, driver and a collection which link the two others)?

  3. To rebuild my objects I have to parse my JSON with the JSON object?

Thanks for your help


Solution

  • Three good questions. I'll answer each in turn.

    1. Did we have to create an index or we can just use the _id which is auto generated?

    You should definitely try and (re)use the _id index. This usually means moving one of the unique fields (or primary key, in RDMS speak) in your domain object to be mapped to the _id field. You do have to be careful that the field does not get to large if you will be sharding but that is a separate question to answer.

    1. If I have for example 2 kind of objects (cars and drivers) with a n-n relation between. I have to get 3 collections(car, driver and a collection which link the two others)?

    No! You only need two collections. One for the cars and one for the drivers. The "join table" is pulled into each of the collections as DBRefs.

    Each car document will contain an array of DBRef or document references. Those references contain the database name (optional), collection name and _id for a driver document. You will have a similar set of DBRefs in the driver document to each of the driven cars.

    Most of the drivers have support for creating and de-referencing these document references.

    1. To rebuild my objects I have to parse my json with the JSON object?

    MongoDB lingua franca is actually BSON. You can think of BSON as a typed, binary, easily parsed version of JSON. Most of the drivers have some capability to convert from JSON to their representation of BSON and back. If you are developing in Java then the 10gen driver's utility class is JSON. For the Asynchronous driver it is called Json.

    Having said that, unless your data is already JSON I would not convert your data to JSON to convert it to BSON and back again. Instead either look for a ODM (Object-Document-Mapper) for your language of choice or perform the translation for your domain object to the driver's BSON representation directly.

    HTH- Rob.