can I save every objects in one collection in mongodb?

collections, mongodb

Solution

Because MongoDB collections are heterogeneous, it is technically possible to store documents in one collection which have nothing to do with each other. But having separate collections for separate classes of documents has the advantage that you can easily isolate these documents from each other.

In your example, where you have animals and ships, it is unlikely that you will have search queries which are supposed to return animals AND ships. Most queries will likely return one or more documents either from the set of animals or from the set of ships.

Imagine in your example, that you would like to have a list of all animals which are different types of Sharks. So you do `db.collection.find({type:"Shark"}`. But unfortunately you weren't aware that there is also a type of sailboat named "Shark". So while you expected to get a number of carnivorous fish, you have a few sailboats in between. Ships lack some fields you expect in the documents returned, like `habitat` and `preferred_food`, so this might cause your application to crash.

This could of course be mitigated by adding another mandatory field to each document `class:"animal"` and `class:"ship"` and make sure that each find-query specifies the class, but that would essentially be reinventing collections.

Another reason to isolate documents by collections is that it makes it easier to apply good indices. Your application might frequently search for ships by type but animals only by name. So it would make sense to have an index on name for all objects where class=animal and another index on type for all objects where class=ship. But unless you put these documents in different collections, you won't be able to do that, so each document will have at least one unnecessary index which needs to be kept up-to-date with every write operation. This becomes quite ridiculous when you have millions of animals in your database but only a dozen or so of ships. It would be quite wasteful when all animals would carry an index around which only applies to ships.

Problem

What is the best practice for using collection? Since the collection is not scheme enforced,why don't save every objects in one collection? there could by objects like ``` {USS_NewYork:{type:"BattleShip"}} {USS_Enterprise:{type:"Carrier"}} {dog:{type:"Mammal"}} ``` I could save the ships and dog in one collection and find the right object easily,so Why I must divied those objects to different collections? But if I always save objects in one collection, why the mongodb implied the collection?

Original source