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 project specific elements in an array field with MongoDB?
To project specific elements in an array field in MongoDB, use the $project stage with $filter to conditionally include array elements that match your criteria.
Syntax
db.collection.aggregate([
{
$project: {
arrayField: {
$filter: {
input: "$arrayField",
as: "item",
cond: { condition }
}
}
}
}
]);
Sample Data
db.demo355.insertOne({
"id": 101,
"details": [
{"Name": "Chris", "isMarried": 1},
{"Name": "David", "isMarried": 0},
{"Name": "Mike", "isMarried": 1}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e568928f8647eb59e5620c5")
}
Display all documents from the collection ?
db.demo355.find().pretty();
{
"_id": ObjectId("5e568928f8647eb59e5620c5"),
"id": 101,
"details": [
{
"Name": "Chris",
"isMarried": 1
},
{
"Name": "David",
"isMarried": 0
},
{
"Name": "Mike",
"isMarried": 1
}
]
}
Example: Filter Married Persons
Project only the array elements where isMarried equals 1 ?
db.demo355.aggregate([
{
$project: {
details: {
$filter: {
input: "$details",
as: "out",
cond: { $eq: ["$$out.isMarried", 1] }
}
}
}
}
]);
{
"_id": ObjectId("5e568928f8647eb59e5620c5"),
"details": [
{ "Name": "Chris", "isMarried": 1 },
{ "Name": "Mike", "isMarried": 1 }
]
}
Key Points
-
$filterreturns only array elements that satisfy the condition. - Use
$$variableNameto reference the alias defined in theasfield. - The
$projectstage reshapes the document structure.
Conclusion
The $project stage with $filter allows selective projection of array elements based on specific conditions. This approach efficiently filters array content while maintaining the document structure.
Advertisements
