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
MongoDB query for Partial Object in an array
To query for a partial object in a MongoDB array, use dot notation to match specific fields within array elements or use the $elemMatch operator for more complex conditions.
Syntax
// Dot notation for single field
db.collection.find({"arrayName.fieldName": "value"});
// $elemMatch for multiple conditions
db.collection.find({"arrayName": {$elemMatch: {"field1": "value1", "field2": "value2"}}});
Sample Data
db.queryForPartialObjectDemo.insertMany([
{
"StudentDetails": [
{"StudentId": 1, "StudentName": "Chris"}
]
},
{
"StudentDetails": [
{"StudentId": 2, "StudentName": "David"}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cdfcf55bf3115999ed51206"),
ObjectId("5cdfcf55bf3115999ed51207")
]
}
Method 1: Using Dot Notation (Recommended)
Query for documents where StudentName is "Chris" ?
db.queryForPartialObjectDemo.find({"StudentDetails.StudentName": "Chris"});
{
"_id": ObjectId("5cdfcf55bf3115999ed51206"),
"StudentDetails": [
{
"StudentId": 1,
"StudentName": "Chris"
}
]
}
Method 2: Using $elemMatch
Query for exact object match within the array ?
db.queryForPartialObjectDemo.find({
"StudentDetails": {$elemMatch: {"StudentId": 1, "StudentName": "Chris"}}
});
{
"_id": ObjectId("5cdfcf55bf3115999ed51206"),
"StudentDetails": [
{
"StudentId": 1,
"StudentName": "Chris"
}
]
}
Key Differences
- Dot notation is simpler for single field queries within arrays
- $elemMatch is required when matching multiple fields on the same array element
- Use
$elemMatchwhen you need to ensure all conditions apply to the same array element
Conclusion
Use dot notation for simple partial object queries in arrays. For complex conditions involving multiple fields, use $elemMatch to ensure all criteria match the same array element.
Advertisements
