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 find a certain element in the MongoDB embedded document?
To find a certain element in a MongoDB embedded document, use the aggregation pipeline with $unwind to flatten the array, $match to filter specific elements, and $project to select desired fields.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.field": "value" } },
{ $project: { "arrayField.desiredField": 1 } }
])
Sample Data
db.demo744.insertOne({
studentInformation: [
{
studentName: "Robert",
grade: "A"
},
{
studentName: "Bob",
grade: "C"
},
{
studentName: "John",
grade: "B"
},
{
studentName: "Sam",
grade: "A"
}
]
})
{
"acknowledged": true,
"insertedId": ObjectId("5ead928a57bb72a10bcf0684")
}
View Sample Data
db.demo744.find()
{
"_id": ObjectId("5ead928a57bb72a10bcf0684"),
"studentInformation": [
{ "studentName": "Robert", "grade": "A" },
{ "studentName": "Bob", "grade": "C" },
{ "studentName": "John", "grade": "B" },
{ "studentName": "Sam", "grade": "A" }
]
}
Example: Find Students with Grade "A"
db.demo744.aggregate([
{ $unwind: "$studentInformation" },
{ $match: { "studentInformation.grade": "A" } },
{ $project: { "studentInformation.studentName": 1 } }
])
{ "_id": ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation": { "studentName": "Robert" } }
{ "_id": ObjectId("5ead928a57bb72a10bcf0684"), "studentInformation": { "studentName": "Sam" } }
How It Works
-
$unwindcreates separate documents for each array element -
$matchfilters documents based on embedded field conditions -
$projectselects only the required fields from the results
Conclusion
Use aggregation pipeline with $unwind, $match, and $project to find and extract specific elements from embedded documents. This approach effectively searches within array fields and returns only matching elements.
Advertisements
