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
How do I index "or" in MongoDB for indexing multiple fields?
To index multiple fields in MongoDB, use createIndex() (or the deprecated ensureIndex()) with a combination of fields. This creates compound indexes that can efficiently support queries on multiple field combinations.
Syntax
db.collection.createIndex({
"field1": 1,
"field2": 1,
"field3": -1
});
Where 1 indicates ascending order and -1 indicates descending order.
Create Sample Data
First, let's insert sample documents into the collection ?
db.demo53.insertMany([
{"StudentFirstName": "Chris", "StudentAge": 21, "StudentCountryName": "US"},
{"StudentFirstName": "David", "StudentAge": 23, "StudentCountryName": "UK"},
{"StudentFirstName": "Mike", "StudentAge": 24, "StudentCountryName": "AUS"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e271431cfb11e5c34d89911"),
ObjectId("5e27143ccfb11e5c34d89912"),
ObjectId("5e27144bcfb11e5c34d89913")
]
}
Example 1: Index on Name and Age
Create a compound index on StudentFirstName and StudentAge ?
db.demo53.createIndex({"StudentFirstName": 1, "StudentAge": 1});
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Example 2: Index on Name and Country
Create another compound index on StudentFirstName and StudentCountryName ?
db.demo53.createIndex({"StudentFirstName": 1, "StudentCountryName": 1});
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 2,
"numIndexesAfter": 3,
"ok": 1
}
Verify Data
Display all documents to confirm the data ?
db.demo53.find();
{ "_id": ObjectId("5e271431cfb11e5c34d89911"), "StudentFirstName": "Chris", "StudentAge": 21, "StudentCountryName": "US" }
{ "_id": ObjectId("5e27143ccfb11e5c34d89912"), "StudentFirstName": "David", "StudentAge": 23, "StudentCountryName": "UK" }
{ "_id": ObjectId("5e27144bcfb11e5c34d89913"), "StudentFirstName": "Mike", "StudentAge": 24, "StudentCountryName": "AUS" }
Key Points
- Compound indexes support queries on multiple field combinations efficiently.
- Field order in the index matters - queries should match the index prefix for optimal performance.
- Use
createIndex()instead of the deprecatedensureIndex()method.
Conclusion
Compound indexes in MongoDB allow efficient querying across multiple fields. Create them using createIndex() with multiple field specifications to optimize query performance for your specific use cases.
