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
MongoDB Indexes - Is it possible to create both normal & compound at the same time?
Yes, you can create both normal (single field) and compound (multiple field) indexes simultaneously in MongoDB using the createIndex() method. MongoDB provides complete support for indexes on any field in a collection of documents.
Syntax
db.collection.createIndex({field1: 1, field2: 1, field3: 1});
Where 1 indicates ascending order and -1 indicates descending order.
Example
Let us create a compound index on multiple fields and insert sample documents ?
db.demo622.createIndex({_id: 1, Name: 1, Age: 1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Sample Data
db.demo622.insertMany([
{_id: 101, Name: "Chris", Age: 21},
{_id: 102, Name: "Chris", Age: 22},
{_id: 103, Name: "Bob", Age: 21},
{_id: 104, Name: "Chris", Age: 22},
{_id: 105, Name: "David", Age: 25}
]);
{
"acknowledged" : true,
"insertedIds" : [101, 102, 103, 104, 105]
}
Display Documents
db.demo622.find();
{ "_id" : 101, "Name" : "Chris", "Age" : 21 }
{ "_id" : 102, "Name" : "Chris", "Age" : 22 }
{ "_id" : 103, "Name" : "Bob", "Age" : 21 }
{ "_id" : 104, "Name" : "Chris", "Age" : 22 }
{ "_id" : 105, "Name" : "David", "Age" : 25 }
Key Points
- A compound index includes multiple fields in a single index structure
- MongoDB automatically creates a single field index on
_idby default - The compound index supports efficient queries on any prefix of the indexed fields
- Field order in compound indexes matters for query optimization
Conclusion
MongoDB allows creating compound indexes that span multiple fields simultaneously. This provides efficient querying capabilities for complex search patterns while maintaining good performance across different field combinations.
Advertisements
