Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I have multiple collections in a NoSql database (MongoDB)

Tags:

mongodb

nosql

Example: If I have a database, let's call it world, then I can have a collection of countries.

The collection can have documents, one example on a document:

"_id" : "hiqgfuywefowehfnqfdqfe",
"name" : "Italy",
cities : {{"_id": "ihevfbwyfv", name : "Napoli"}, {"_id: "hjbyiu", name: "Milano"}}

Why should I or when should I create a new collection of documents, I could expand my documents inside my world collection instead of creating a new collection.

Is creating a new collection not like creating a new domain?

like image 804
yusuf tezel Avatar asked Jan 20 '26 10:01

yusuf tezel


1 Answers

A world collection should look like this: You should create a document / country. The above is a single document:

{
  "_id": "objectKey", //generated by mongo
  "countryName": "Italy",
  "cities":[
    {
      "id": 1,
      "cityName": "Napoli"
    },
    {
      "id": 2,
      "cityName": "Milano"
    }
  ],
}

Try to expend this collection with other countrys but there are some other situations where you should consider creating a new collection and try to create some sort of relation:

  • If you use mmapv1 storage engine and you wish to add cities over the time you should consider relational way cuz mmapv1 does not tolerate rapidly growing arrays. If you create a document with mmapv1 the storage engine gives a paddign to the document for growing arrays. If this paddign is filled then the document will be relocated in the hard drive with will result disc fregmentation and performace loss. Btw the default storage is Wiredtiger now which does not have this problem.
  • Do not nest documents too deeply. It will make your documents hard to run complex queries on. For an example do not create documents like the following:

    { "continentName": "Europe", "continentCountries: [ { "countryName": "France", "cities": [ { "cityId": 1, "cityName": "Paris" }, { another country } ] }, { another country } ], "TimeZone": "GMT+1" ], "continentId": 1 } In this situtation you should create a continent property for your country object with the continent name or id in it. With mongodb you should avoid relations most of the time but its not forbidden to create them. Its way better to create relation then nest document too deeply but the best solution is to flip hierarchical level of the document documents for an example:

use 'county->cities, countinentId, etc...' instead of 'continent->country->city'

useful reading: https://docs.mongodb.org/manual/core/data-modeling-introduction/

like image 173
kailniris Avatar answered Jan 22 '26 01:01

kailniris