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 use arrays as filters by querying subdocuments in MongoDB?
To use arrays as filters when querying subdocuments in MongoDB, use the $setIsSubset operator within an aggregation pipeline. This operator checks if one array is a subset of another, making it useful for filtering array elements based on specific values.
Syntax
db.collection.aggregate([
{ $project: {
"arrayField": {
$filter: {
input: "$arrayField",
as: "item",
cond: { $setIsSubset: [["$$item.field"], [filterValues]] }
}
}
}}
]);
Sample Data
db.demo407.insertMany([
{
"Name": "Chris",
"details": [
{ "id": 100 },
{ "id": 110 },
{ "id": 130 }
]
},
{
"Name": "John",
"details": [
{ "id": 120 },
{ "id": 140 },
{ "id": 100 }
]
}
]);
View Sample Data
db.demo407.find();
[
{
"_id": ObjectId("5e70dffe15dc524f70227677"),
"Name": "Chris",
"details": [
{ "id": 100 },
{ "id": 110 },
{ "id": 130 }
]
},
{
"_id": ObjectId("5e70dffe15dc524f70227678"),
"Name": "John",
"details": [
{ "id": 120 },
{ "id": 140 },
{ "id": 100 }
]
}
]
Example: Filter Subdocuments by ID Values
Filter documents to show only subdocuments with IDs 100 or 130 ?
db.demo407.aggregate([
{ $match: {} },
{ $project: {
"Name": 1,
"details": {
$filter: {
input: "$details",
as: "output",
cond: { $setIsSubset: [["$$output.id"], [100, 130]] }
}
}
}}
]);
[
{
"_id": ObjectId("5e70dffe15dc524f70227677"),
"Name": "Chris",
"details": [
{ "id": 100 },
{ "id": 130 }
]
},
{
"_id": ObjectId("5e70dffe15dc524f70227678"),
"Name": "John",
"details": [
{ "id": 100 }
]
}
]
How It Works
-
$filterprocesses each element in the details array -
$setIsSubsetchecks if the subdocument's ID exists in the filter array [100, 130] - Only matching subdocuments are included in the result
- The
$$output.idreference accesses each subdocument's id field
Conclusion
Use $setIsSubset with $filter in aggregation pipelines to filter subdocuments based on array values. This approach efficiently queries nested documents while preserving the document structure.
Advertisements
