mongodbdocument-oriented-db

How to avoid inconsistent embedded documents


Having a bit of trouble understanding when and why to use embedded documents in a mongo database.

Imagine we have three collections: users, rooms and bookings.

inconsistent embed

I have a few questions about a situation like this:

1) How would you update the embedded document? Would it be the responsibility of the application developer to find all instances of kevin as a embedded document and update it?

2) If the solution is to use document references, is that as heavy as a relational db join? Is this just a case of the example not being a good fit for Mongo?

As always let me know if I'm being a complete idiot.


Solution

  • Imho, you overdid it. Given the question from you use cases are

    I would go with the following model for rooms

    {
      _id: 1001,
      beds: 2
    }
    

    for users

    {
       _id: new ObjectId(),
       username: "Kevin",
       mobile:"12345678"
     }
    

    and for reservations

    {
       _id: new ObjectId(),
       date: new ISODate(),
       user: "Kevin",
       room: 1001
    }
    

    Now in a reservation overview, you can have all relevant information ("who", "when" and "which") by simply querying reservations, without any overhead to answer the first question from you use cases. In a reservation details view, admittedly you would have to do two queries, but they are lightning fast with proper indexing and depending on your technology can be done asynchronously, too. Note that I saved an index by using the room number as id. How to answer the remaining questions should be obvious.

    So as per your original question: embedding is not necessary here, imho.