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 array elements in MongoDB?
To filter array elements in MongoDB, you can use the $setIntersection operator within the aggregation framework. This operator returns elements that exist in both the original array and your filter criteria array.
Syntax
db.collection.aggregate([
{ $project: {
fieldName: {
$setIntersection: ["$arrayField", [filterValues]]
}
}}
]);
Sample Data
db.filterArrayElementsDemo.insertOne({
"Scores": [10, 45, 67, 78, 90, 98, 99, 92]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd2d582b64f4b851c3a13c8")
}
Display the document to verify the data ?
db.filterArrayElementsDemo.find().pretty();
{
"_id": ObjectId("5cd2d582b64f4b851c3a13c8"),
"Scores": [
10,
45,
67,
78,
90,
98,
99,
92
]
}
Example: Filter Specific Values
Filter the Scores array to return only values 10, 98, and 99 ?
db.filterArrayElementsDemo.aggregate([
{ $match: {
_id: ObjectId("5cd2d582b64f4b851c3a13c8")
}},
{ $project: {
Scores: {
$setIntersection: ["$Scores", [10, 98, 99]]
}
}}
]);
{ "_id": ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores": [10, 98, 99] }
Key Points
-
$setIntersectionreturns elements that exist in both arrays - The result maintains the order from the original array
- Use
$matchto target specific documents before filtering
Conclusion
The $setIntersection operator provides an efficient way to filter array elements by finding common values between the original array and your filter criteria. This method works well for exact value matching within aggregation pipelines.
Advertisements
