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 can I find documents in MongoDB based on the number of matched objects within an array?
In MongoDB, you can find documents based on the number of matched objects within an array using aggregation pipelines with $filter and $size operators, or the $where operator for JavaScript-based queries.
Syntax
// Method 1: Using Aggregation Pipeline
db.collection.aggregate([
{ $match: {
$expr: { $gte: [
{ $size: { $filter: {
input: "$arrayField",
cond: { $and: [ /* conditions */ ] }
}}},
minCount
]}
}}
]);
// Method 2: Using $where operator
db.collection.find({ $where: function() {
// JavaScript logic to count matches
}});
Sample Data
db.demo694.insertMany([
{
"details": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "David", "Age": 22 }
]
},
{
"details": [
{ "Name": "Bob", "Age": 21 },
{ "Name": "Mike", "Age": 23 }
]
},
{
"details": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "Carol", "Age": 22 }
]
}
]);
Method 1: Using Aggregation Pipeline (Recommended)
db.demo694.aggregate([
{
$match: {
$expr: {
$gte: [
{
$size: {
$filter: {
input: "$details",
cond: {
$and: [
{ $eq: ["$$this.Name", "Chris"] },
{ $eq: ["$$this.Age", 21] }
]
}
}
}
},
1
]
}
}
}
]);
Method 2: Using $where Operator
nameChrisAge21 = function () {
var count = 0;
this.details.forEach(function (d) {
if (d.Name == "Chris" && d.Age == 21) {
count++;
}
});
return count >= 1;
}
db.demo694.find({ $where: nameChrisAge21 });
{ "_id" : ObjectId("5ea59279ece4e5779399c07f"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 } ] }
{ "_id" : ObjectId("5ea5927aece4e5779399c081"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Carol", "Age" : 22 } ] }
Key Points
- The aggregation method is preferred for performance as it uses MongoDB's optimized operators.
-
$filtercreates an array of matching elements, and$sizecounts them. -
$whereexecutes JavaScript but is slower and cannot use indexes effectively.
Conclusion
Use aggregation pipelines with $filter and $size for efficient array element counting. The $where operator provides flexibility but sacrifices performance for complex JavaScript logic.
Advertisements
