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
How to improve MongoDB queries with multikey index in array?
To improve MongoDB queries with multikey index in array fields, use $elemMatch operator combined with proper compound indexes on array elements. This ensures efficient querying of nested objects within arrays.
Syntax
db.collection.find({
"arrayField": {
$elemMatch: {
"field1": "value1",
"field2": "value2"
}
}
});
Sample Data
db.demo444.insertMany([
{
"Information": [{
id: 1,
Name: "Chris"
}]
},
{
"Information": [{
id: 2,
Name: "David"
}]
},
{
"Information": [{
id: 3,
Name: "Bob"
}]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e78ea87bbc41e36cc3caebf"),
ObjectId("5e78ea87bbc41e36cc3caec0"),
ObjectId("5e78ea88bbc41e36cc3caec1")
]
}
Display All Documents
db.demo444.find();
{ "_id": ObjectId("5e78ea87bbc41e36cc3caebf"), "Information": [ { "id": 1, "Name": "Chris" } ] }
{ "_id": ObjectId("5e78ea87bbc41e36cc3caec0"), "Information": [ { "id": 2, "Name": "David" } ] }
{ "_id": ObjectId("5e78ea88bbc41e36cc3caec1"), "Information": [ { "id": 3, "Name": "Bob" } ] }
Query with $elemMatch for Multikey Index
db.demo444.find({
"Information": {
$elemMatch: {
id: 2,
Name: "David"
}
}
});
{ "_id": ObjectId("5e78ea87bbc41e36cc3caec0"), "Information": [ { "id": 2, "Name": "David" } ] }
Create Multikey Index for Optimization
db.demo444.createIndex({
"Information.id": 1,
"Information.Name": 1
});
Key Points
-
$elemMatchensures all conditions match within the same array element. - Multikey indexes on array fields automatically index each array element separately.
- Compound indexes on nested fields improve query performance significantly.
Conclusion
Use $elemMatch with proper compound indexes on array fields to optimize MongoDB queries. This combination ensures efficient filtering and leverages multikey indexing for better performance on nested array elements.
Advertisements
