Mongoid Cheat Sheet

MongoDB is the next-generation database that helps businesses transform their industries by harnessing the power of data.

That is how the creators of MongoDB describe their database. And YES, MongoDB is truly amazing. Its write speed is blazing fast but you need to know how to deal with it. I am not a MongoDB expert but I will share my knowledge about Mongoid.

Before we start I would advice you to use Mongoid 5.0.0 or above since they contain a lot of interesting and helpful updates.

  • The mongoid.yml file should be structured in this way

      development:
        clients:
          default:
            database: my_development
            hosts:
              - localhost:27017
    

If you were using a Mongoid version that precedes 5.0.0, please change the old sessions to clients as shown above.

  • Bulk Inserting
    To insert multiple documents to a MongoDB collection and you do not care about your model's callbacks, you should use Model.collection.insert_many
    For example, If you have a model Company with fields name and revenue, you can bulk insert multiple documents as follows

      Company.collection.insert_many({name: "C1", revenue: 1000}, {name: "C2", revenue: 2000}, {name: "C3", revenue: 3000}, {name: "C4", revenue: 4000}, {name: "C5", revenue: 5000})
    

Instead of doing

    Company.create(name: "C1", revenue: 1000)
    Company.create(name: "C2", revenue: 2000)
    Company.create(name: "C3", revenue: 3000)
    Company.create(name: "C4", revenue: 4000)
    Company.create(name: "C5", revenue: 5000)

The later will fire the models' callbacks though!

  • The difference between Model.destroy_all and Model.delete_all is that destroy_all fires callbacks for each destroyed model while delete_all does not.

  • Model.collection.delete_many bulk deletes documents from a collection. It can be used as follows

      array_of_names = ["C1", "C2", "C3"]
      Company.collection.delete_many({name: { :$in => array_of_names}})
    

To be continued and you can ask for anything in the comments section.