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 filter some fields in objects and fetch a specific subject name value in MongoDB?
To filter and fetch specific fields from objects in MongoDB, use the aggregation pipeline combining $match, $project, and $filter operators to target specific array elements and extract only the desired fields.
Syntax
db.collection.aggregate([
{ $match: { "arrayField.field": "value" } },
{ $project: {
arrayField: {
$filter: {
input: "$arrayField",
as: "item",
cond: { $eq: ["$$item.field", "value"] }
}
}
}},
{ $project: { "arrayField.specificField": 1 } }
]);
Sample Data
db.demo507.insertOne({
"Information": [
{"Name": "John", "SubjectName": "MySQL"},
{"Name": "Bob", "SubjectName": "MongoDB"},
{"Name": "Chris", "SubjectName": "MySQL"},
{"Name": "David", "SubjectName": "C++"}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e8836d3987b6e0e9d18f577")
}
Example: Filter MySQL Subjects and Show Only SubjectName
To filter objects with SubjectName "MySQL" and return only the SubjectName field ?
db.demo507.aggregate([
{ $match: { "Information.SubjectName": "MySQL" } },
{ $project: {
_id: 0,
Information: {
$filter: {
input: "$Information",
as: "result",
cond: { $eq: ["$$result.SubjectName", "MySQL"] }
}
}
}},
{ $project: { Information: { SubjectName: 1 } } }
]);
{ "Information": [ { "SubjectName": "MySQL" }, { "SubjectName": "MySQL" } ] }
How It Works
-
$matchfilters documents containing MySQL subjects -
$filterextracts only array elements matching the condition - Final
$projectreturns only the SubjectName field from filtered results
Conclusion
Use the aggregation pipeline with $match, $filter, and $project to filter array elements and extract specific fields. This approach efficiently handles complex filtering and field selection in nested documents.
Advertisements
