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
Filter specific values from a MongoDB document
To filter specific values from a MongoDB document, use the $filter operator in aggregation pipelines. This operator allows you to select array elements that match specific conditions and return only those elements.
Syntax
{
$filter: {
input: "$arrayField",
as: "variable",
cond: { condition }
}
}
Sample Data
db.demo751.insertOne({
_id: 101,
details: [
{ Name: "Robert", id: 110, Age: 21 },
{ Name: "Rae", id: 110, Age: 22 },
{ Name: "Ralph", id: 116, Age: 23 }
]
});
{ "acknowledged": true, "insertedId": 101 }
Example 1: Filter by Specific ID Value
Filter documents where the id field equals 110 and get only the last matching element ?
db.demo751.aggregate([
{
$addFields: {
details: {
$let: {
vars: {
filtered: {
$filter: {
input: "$details",
as: "out",
cond: { $eq: ["$$out.id", 110] }
}
}
},
in: { $slice: ["$$filtered", -1] }
}
}
}
}
]);
{ "_id": 101, "details": [{ "Name": "Rae", "id": 110, "Age": 22 }] }
Example 2: Simple Filter Without $slice
Get all elements where id equals 110 ?
db.demo751.aggregate([
{
$addFields: {
filteredDetails: {
$filter: {
input: "$details",
as: "item",
cond: { $eq: ["$$item.id", 110] }
}
}
}
}
]);
{
"_id": 101,
"details": [...],
"filteredDetails": [
{ "Name": "Robert", "id": 110, "Age": 21 },
{ "Name": "Rae", "id": 110, "Age": 22 }
]
}
Key Points
-
$filterreturns an array of matching elements based on the specified condition. -
$slicecan be used with$filterto get specific elements (first, last, etc.). - Use
$$variablesyntax to reference the iterator variable in conditions.
Conclusion
The $filter operator is essential for extracting specific array elements in MongoDB. Combine it with $slice for precise element selection or use it standalone to get all matching elements.
Advertisements
