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
Search for documents matching first item in an array with MongoDB?
To search for documents matching the first item in an array in MongoDB, use dot notation with index 0 to target the first element directly. This approach allows you to query specific fields within the first array element.
Syntax
db.collection.find({"arrayName.0.fieldName": "value"});
Sample Data
db.matchingFirstItemInTheArrayDemo.insertMany([
{
"ClientDetails": [
{
"ClientName": "Larry",
"ClientAge": 28
}
]
},
{
"ClientDetails": [
{
"ClientName": "Chris",
"ClientAge": 56
}
]
},
{
"ClientDetails": [
{
"ClientName": "Robert",
"ClientAge": 46
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd7a5d26d78f205348bc636"),
ObjectId("5cd7a5f56d78f205348bc637"),
ObjectId("5cd7a6076d78f205348bc638")
]
}
Example: Search by First Item Field
Find documents where the first client's name is "Chris" ?
db.matchingFirstItemInTheArrayDemo.find({"ClientDetails.0.ClientName": "Chris"});
{
"_id": ObjectId("5cd7a5f56d78f205348bc637"),
"ClientDetails": [
{
"ClientName": "Chris",
"ClientAge": 56
}
]
}
Key Points
-
arrayName.0specifically targets the first element of the array (index 0). - This method only matches if the specified field exists in the first array position.
- Use this approach when array order matters and you need to query the first element specifically.
Conclusion
Use dot notation with index 0 to search documents based on the first item in an array. This precise targeting ensures you match only the first element, making it ideal for ordered array queries.
Advertisements
