Question

I have working experience with relational databases and recently I started learning MongoDB. I have a basic question:

Suppose I want to insert a Row/Document in a Table/Collection. What I can see is:

For Relational Database:

If the insert query contains a column which does not exists in the table, then the insertion is failed and an error is thrown.

For MongoDB

db.<CollectionName>.insert({"Key 1":"value 1", .... , "Key N":"value N"})

For different Key, a new Field is getting created in that Document. Hence we don't have any restriction with the number of Field applicable for a Collection right (unlike the Relational Databases) - WHY?

1) From relational database prospective, this should not have worked. What if the developer by mistake (typo mistake) inserts a record having a different key name? This will unnecessarily create an extra Field right?

2) How this can be restricted so that only a few specific Field can be inserted in a Document (Not sure if this is the correct way for working with MongoDB) ?

Please clarify, I am fairly confused on my first learning day.

Was it helpful?

Solution

Key names in MongoDB that are not identical do not match. If two documents contain identical key/value pairs in different order, they do not match. MongoDB is schemaless by design. It increases speed to simply insert and fetch entire documents from disk. MongoDB gets performance and scalability from saving complex and time consuming operations like transactions, data validation, etc. The savings are basically passed on to the developer (and the end user), but if you think about how SQL/RDBMS work in the real world, the application developer has to do all kinds of validation anyway.

As to your question about typos: how could you introduce a typo into a key? Is your code being generated by humans on the fly? Once it's compiled, it'll just run until you or someone else modifies it. When (if ever) you start seeing inconsistencies, you can modify those documents that have typos pretty easily. Mongo even has background updates for this purpose.

Although MongoDB is schemaless, your code will nevertheless enforce a de facto schema. But your anxiety isn't necessary, I think. Mongo has a really flexible and powerful aggregation framework that makes searching and aggregating documents easy (and fast).


Edit 1: There is a restriction of 16MB per document, so you can't keep adding keys forever. Thought that should be mentioned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top