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 do I return a document with filtered sub-documents using Mongo?
To return a document with filtered sub-documents in MongoDB, use the $project stage with $filter operator in an aggregation pipeline. The $filter operator allows you to select specific array elements based on conditions while preserving the document structure.
Syntax
db.collection.aggregate([
{
$project: {
arrayField: {
$filter: {
input: "$arrayField",
as: "item",
cond: { condition }
}
}
}
}
])
Create Sample Data
db.demo457.insertMany([
{
_id: 101,
details: [
{ ProductName: "Product-1", ProductPrice: 90 },
{ ProductName: "Product-2", ProductPrice: 190 }
]
},
{
_id: 102,
details: [
{ ProductName: "Product-3", ProductPrice: 150 },
{ ProductName: "Product-4", ProductPrice: 360 }
]
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": 101,
"1": 102
}
}
View All Documents
db.demo457.find();
{ "_id": 101, "details": [ { "ProductName": "Product-1", "ProductPrice": 90 }, { "ProductName": "Product-2", "ProductPrice": 190 } ] }
{ "_id": 102, "details": [ { "ProductName": "Product-3", "ProductPrice": 150 }, { "ProductName": "Product-4", "ProductPrice": 360 } ] }
Example: Filter Products by Price ? 170
db.demo457.aggregate([
{
$project: {
details: {
$filter: {
input: "$details",
as: "output",
cond: { $gte: [ "$$output.ProductPrice", 170 ] }
}
}
}
}
]);
{ "_id": 101, "details": [ { "ProductName": "Product-2", "ProductPrice": 190 } ] }
{ "_id": 102, "details": [ { "ProductName": "Product-4", "ProductPrice": 360 } ] }
How It Works
-
input− The array field to filter ("$details") -
as− Variable name for each array element ("output") -
cond− Filter condition using "$$output" to reference current element
Conclusion
Use $project with $filter to return documents containing only array elements that match specific criteria. This preserves the original document structure while filtering sub-document arrays based on conditions.
Advertisements
