i would like to store a lot of data in the database. So I hope that I can use the index to do the filtering.
My current idea is, when I apply the index, mongodb only search for the data with the same index. So, it can save a lot time and resources.
Below is my data that i want to save into database
{ "name": "Mr A","type": "Individual","country": "Nepal"}
{ "name": "Mr B","type": "Individual","country": "Singapore"}
{ "name": "Company C","type": "Corporate","country": "Singapore"}
So when i save, how do I create index when i save the date?
const customer = new Customer({ "name": "Mr A","type": "Individual,"country": "Nepal"});
await customer.save()
const customer2 = new Customer({ "name": "Mr B","type": "Individual","country": "Singapore"});
await customer2.save()
const customer3 = new Customer({ "name": "Company C","type": "Corporate","country": "Singapore"});
await customer3.save()
// Create index now and how?
// hope to create index
So, when i do the search
const findCustomer = await Customer.find({type: "Individual"}).explain("executionStats")
I hope that, mongodb only "totalDocsExamined" only 2 document instead of 3
2
Answers
You can create an index using the ensureIndexes() method, you can create an index on the "type" field.
Indexes can be defined on the path where you declare each property like so:
Or you can define them on the schema like so:
Be careful with the
type
property you have declared. In mongoosetype
has a special meaning in a schema and can be the source of unexpected behaviour if you don’t understand the data correctly.