Mongo DB as part of MERN Stack

Why do people use Mango DB?

Schema

Unlike relational database, MongoDB does not require a predefined schema. This feature allow us to store documents with varying data structures. This flexibility also eliminates the need for complex JOIN operations, as related data can be embedded directly within a single document.

MongoDB can efficiently produce aggregated results without incurring the overhead typically associated with joins in relational databases.

Indexing

Using the combination of single field index, compound index, and build-in query optimizing tool, we can further enhance query performance.

db.products.createIndex({ category: 1, tags: 1, price: -1 });

Here’s some example of CRUD operation performed on the Mongo DB.

Create

db.products.insertMany([ { name: "Headphones", price: 150, category: "Electronics", inStock: true, details: { brand: "Sony", "noiseCancelling": true } }, { name: "Notebook", price: 5, category: "Office Supplies", inStock: true } ])

Read

db.products.find({ price: { $gt: 50 } })

Update

db.products.updateMany( { category: "Books" }, { $set: { inStock: false } } )

Delete

db.products.deleteMany({ category: "Office Supplies" })

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *