26
Lightning Fast MongoDB Data Query : Part - 1
Databases store hundreds and thousands of data. Querying a document from a huge database is often time consuming.
How many times have you found yourself watching the loading spinner while your website loads?
As a Developer you don't want this to happen to your site right?
But hiring Database engineers is not for us, we want to do it free of cost!!
Well here are a few simple tricks or features that you can use to achieve this :
The most obvious solution is to create indexes
for the commonly used query field/fields.
But then what are indexes? If you don't know what Indexes are, follow my Blog 👉 thevinitgupta for a coming soon article on it!!
For now, indexes can be understood as :
The set of
unique IDs
arranged in a specific order.
This allows us to look for a particular data based on a field value is an efficient way.
It is similar to look for a value in an UNSORTED ARRAY
vs in a SORTED ARRAY
.
MongoDB documents are not just plain JSON objects after they are stored in the Database. They have various states and properties that enable us tov use features that we know like Triggers, casting and validation, etc.
This makes a MongoDB document really heavy for parsing over request, thus making queries slower.
There are moments when we just want to read data. Getting all those features are just time and network consuming.
Instead we can use lean()
method in GET
request to reduce these documents as >POJOs - Plain Old JavaScript Objects.
Simple query would look like :
db.posts.find().lean();
- Change tracking
- Casting and validation
- Getters and setters
- Virtuals (including “id”)
- save() function
These are 2 methods for today!!
Do comment if you have any queries regarding these. Also follow for the next part, coming in next Monday at 12PM.
26