Jragon
Jragon

Reputation: 45

Best way to organize JSON data for MongoDB

I come from a relational database background and am still trying to get my head around how to store data that would have been relational in a NoSQL database (or JSON object).

My question is, how would I store data about villages? Each village has a user attached to it, and each village has an X and a Y coordinate. This is what the object might look like:

var map = [{
  x: 1,
  y: 1,
  terrainType: land,
  village: {
    mayor: jragon,
    population: 150,
    gold: 100,
    iron: 25,
    garrason: {
      archers: 4,
      knights: 1
    },
    buildings: {
      smith: {
        level: 4,
        upgradeFinish: false;
      },
      mill: {
        level: 2,
        upgradeFinish: 'some date/time...'
      }
    }
  }
}];

However, as you can probably see it might get a bit out of hand. I guess using some of the mongoose helpers might help when querying for data.

Even with this object there is still some aspect of relation. map.village.mayor refers to a User in a different collection.

The map collection is used to draw the map each time. When drawing the map it decides what tile to use by what level the village is.

Sorry if I haven't made myself clear!

Upvotes: 1

Views: 816

Answers (1)

dotpush
dotpush

Reputation: 428

To have a good schema design in MongoDB, you should really care about the requests you will do frequently.

There are multiple things to take in mind:

  • Your requests should be correct regarding the limits of MongoDB (no transaction, document level atomicity, no real join...)
  • Your requests should ideally be simple to code.
  • You should be able to use indexes the right way. If each request can use an index to read the data you nead and not a lot more, then you've done a good job.
  • The name of the keys are duplicated in each document. You may shorten the names, but I'd rather do it automatically or not at all.

If you want to learn, I'd suggest you at least half of the book "MongoDB Applied Design Patterns" by Rick Copeland. Your question and the context may be too broad to even fit on stackoverflow.

Upvotes: 2

Related Questions