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
Get index of given element in array field in MongoDB?
To get the index of a given element in an array field in MongoDB, use the $indexOfArray operator within an aggregation pipeline. This operator returns the zero-based index of the first occurrence of the specified element in the array.
Syntax
db.collection.aggregate([
{
$project: {
"fieldName": {
$indexOfArray: [ "$arrayField", "searchElement" ]
}
}
}
]);
Sample Data
db.getIndexDemo.insertOne({
"InstructorName": "Chris",
"InstructorSubject": ["MongoDB", "MySQL", "Java", "C++"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cbd5251de8cc557214c0df8")
}
Display all documents from the collection ?
db.getIndexDemo.find().pretty();
{
"_id": ObjectId("5cbd5251de8cc557214c0df8"),
"InstructorName": "Chris",
"InstructorSubject": [
"MongoDB",
"MySQL",
"Java",
"C++"
]
}
Example 1: Find Index of "MongoDB"
db.getIndexDemo.aggregate([
{
$project: {
"matchedIndex": {
$indexOfArray: ["$InstructorSubject", "MongoDB"]
}
}
}
]);
{ "_id": ObjectId("5cbd5251de8cc557214c0df8"), "matchedIndex": 0 }
Example 2: Find Index of "C++"
db.getIndexDemo.aggregate([
{
$project: {
"matchedIndex": {
$indexOfArray: ["$InstructorSubject", "C++"]
}
}
}
]);
{ "_id": ObjectId("5cbd5251de8cc557214c0df8"), "matchedIndex": 3 }
Key Points
-
$indexOfArrayreturns -1 if the element is not found in the array - Array indexing starts from 0, where the first element has index 0
- The operator returns the index of the first occurrence of the element
Conclusion
The $indexOfArray operator efficiently finds the zero-based position of elements in array fields. Use it within aggregation pipelines to locate specific values and perform index-based operations on array data.
Advertisements
