Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Building Multiple Indexes at once in MongoDB?
To build multiple indexes at once in MongoDB, use the createIndexes() method and pass multiple index specifications in an array. This approach is more efficient than creating indexes one by one.
Syntax
db.collection.createIndexes([
{ "field1": 1 },
{ "field2": -1 },
{ "field3": 1, "field4": 1 }
]);
Example
Let's create multiple single-field indexes on a collection ?
db.multipleIndexesDemo.createIndexes([
{"First": 1},
{"Second": 1},
{"Third": 1},
{"Fourth": 1},
{"Fifth": 1}
]);
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 6,
"ok": 1
}
Verify Created Indexes
Use getIndexes() to view all indexes on the collection ?
db.multipleIndexesDemo.getIndexes();
[
{
"v": 2,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "test.multipleIndexesDemo"
},
{
"v": 2,
"key": {
"First": 1
},
"name": "First_1",
"ns": "test.multipleIndexesDemo"
},
{
"v": 2,
"key": {
"Second": 1
},
"name": "Second_1",
"ns": "test.multipleIndexesDemo"
},
{
"v": 2,
"key": {
"Third": 1
},
"name": "Third_1",
"ns": "test.multipleIndexesDemo"
},
{
"v": 2,
"key": {
"Fourth": 1
},
"name": "Fourth_1",
"ns": "test.multipleIndexesDemo"
},
{
"v": 2,
"key": {
"Fifth": 1
},
"name": "Fifth_1",
"ns": "test.multipleIndexesDemo"
}
]
Key Points
-
createIndexes()creates all indexes in a single operation, which is more efficient than multiplecreateIndex()calls. - The method returns the total number of indexes before and after the operation.
- Each index gets an auto-generated name like
fieldName_1for ascending indexes.
Conclusion
Use createIndexes() with an array of index specifications to efficiently create multiple indexes simultaneously. This approach reduces overhead compared to creating indexes individually and provides better performance during bulk index creation.
Advertisements
