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 get the index of an array element in older versions on MongoDB?
To get the index of an array element in older versions of MongoDB, use the $indexOfArray aggregation operator. This operator returns the position (0-based index) of the first occurrence of a specified value in an array, or -1 if the value is not found.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $indexOfArray: ["$arrayField", "searchValue"] }
}
}
]);
Sample Data
db.demo65.insertMany([
{ "ListOfValues": [10, 20, 30] },
{ "ListOfValues": [50, 60, 70, 100] },
{ "ListOfValues": [30, 40, 89, 91, 98] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e28990ecfb11e5c34d89938"),
ObjectId("5e28991ecfb11e5c34d89939"),
ObjectId("5e28992bcfb11e5c34d8993a")
]
}
Display Sample Data
db.demo65.find();
{ "_id": ObjectId("5e28990ecfb11e5c34d89938"), "ListOfValues": [10, 20, 30] }
{ "_id": ObjectId("5e28991ecfb11e5c34d89939"), "ListOfValues": [50, 60, 70, 100] }
{ "_id": ObjectId("5e28992bcfb11e5c34d8993a"), "ListOfValues": [30, 40, 89, 91, 98] }
Example: Find Index of Value 30
db.demo65.aggregate([
{
$project: {
IndexOfAnArrayElement: { $indexOfArray: ["$ListOfValues", 30] }
}
}
]);
{ "_id": ObjectId("5e28990ecfb11e5c34d89938"), "IndexOfAnArrayElement": 2 }
{ "_id": ObjectId("5e28991ecfb11e5c34d89939"), "IndexOfAnArrayElement": -1 }
{ "_id": ObjectId("5e28992bcfb11e5c34d8993a"), "IndexOfAnArrayElement": 0 }
Key Points
-
$indexOfArrayreturns 0-based index of the first match. - Returns -1 when the value is not found in the array.
- Works with
$projectstage in aggregation pipeline.
Conclusion
The $indexOfArray operator provides an efficient way to find element positions in arrays during aggregation. It returns the zero-based index of the first match or -1 if the value doesn't exist in the array.
Advertisements
