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 does MongoDB index arrays?
MongoDB automatically indexes every value within an array field when you create an index on that field. This allows efficient querying of individual array elements without scanning the entire collection.
Syntax
db.collection.createIndex({"arrayField": 1});
db.collection.find({"arrayField": "specificValue"});
Sample Data
Let us create a collection with a document containing an array field ?
db.indexingForArrayElementDemo.insertOne({
"StudentFavouriteSubject": ["MongoDB", "MySQL"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5c8acdca6cea1f28b7aa0816")
}
Display the document to verify ?
db.indexingForArrayElementDemo.find().pretty();
{
"_id": ObjectId("5c8acdca6cea1f28b7aa0816"),
"StudentFavouriteSubject": [
"MongoDB",
"MySQL"
]
}
Creating Array Index
Create an index on the array field ?
db.indexingForArrayElementDemo.createIndex({"StudentFavouriteSubject": 1});
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Querying Individual Array Elements
Query for documents containing "MongoDB" in the array ?
db.indexingForArrayElementDemo.find({"StudentFavouriteSubject": "MongoDB"});
{
"_id": ObjectId("5c8acdca6cea1f28b7aa0816"),
"StudentFavouriteSubject": [
"MongoDB",
"MySQL"
]
}
Query for documents containing "MySQL" in the array ?
db.indexingForArrayElementDemo.find({"StudentFavouriteSubject": "MySQL"});
{
"_id": ObjectId("5c8acdca6cea1f28b7aa0816"),
"StudentFavouriteSubject": [
"MongoDB",
"MySQL"
]
}
How It Works
When MongoDB creates an index on an array field, it automatically creates separate index entries for each array element. This means both "MongoDB" and "MySQL" have their own index entries pointing to the same document.
Conclusion
MongoDB's array indexing automatically creates index entries for every array element, enabling fast queries on individual values. Use createIndex() on array fields to optimize array element searches.
