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 select a specific subdocument in MongoDB?
To select a specific subdocument in MongoDB, use the find() method with dot notation to query array elements and the $ positional operator in projection to return only the matched subdocument.
Syntax
db.collection.find(
{ "arrayField.subfield": "value" },
{ "arrayField.$": 1, "_id": 0 }
);
Sample Data
Let us create a collection with documents containing subdocument arrays ?
db.demo37.insertMany([
{
"Details": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "David", "Age": 23 }
]
},
{
"Details": [
{ "Name": "Sam", "Age": 23 },
{ "Name": "Robert", "Age": 25 }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e176635cfb11e5c34d898d7"),
ObjectId("5e17664acfb11e5c34d898d8")
]
}
Display All Documents
db.demo37.find();
{ "_id": ObjectId("5e176635cfb11e5c34d898d7"), "Details": [ { "Name": "Chris", "Age": 21 }, { "Name": "David", "Age": 23 } ] }
{ "_id": ObjectId("5e17664acfb11e5c34d898d8"), "Details": [ { "Name": "Sam", "Age": 23 }, { "Name": "Robert", "Age": 25 } ] }
Example: Select Specific Subdocument
Select the subdocument where Name is "Sam" using the positional operator ?
db.demo37.find(
{ "Details.Name": "Sam" },
{ "_id": 0, "Details.$": 1 }
);
{ "Details": [ { "Name": "Sam", "Age": 23 } ] }
Key Points
- Use dot notation (
"arrayField.subfield") to query within subdocuments. - The
$positional operator in projection returns only the first matched array element. - Set
_id: 0to exclude the document ID from results.
Conclusion
Combine dot notation queries with the $ positional operator in projection to select specific subdocuments from arrays. This approach returns only the matched subdocument rather than the entire array.
Advertisements
