I have this mongoose schema.
const storeSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
fruits: {
type: [String],
required: true,
},
});
And I need to get all the objects that have 2 or more bananas in the fruits array, like this.
{
"name": "Beautiful Store",
"fruits": ["banana", "apple", "banana", "pear"]
}
I was trying something like this, but with no success…
const query = await StoreModel.find({ fruits: { $gd: 2 } })
>Solution :
Somethign like this:
Option 1: ( less efective but intuitive )
db.collection.aggregate([
{
$addFields: {
numBananas: {
$size: {
$filter: {
input: "$fruits",
as: "item",
cond: {
$eq: [
"$$item",
"banana"
]
}
}
}
}
}
},
{
$match: {
numBananas: {
$gte: 2
}
}
},
{
$project: {
name: 1,
fruits: 1
}
}
])
Explained:
- Add field "numBananas" with the number of bananas
- Filter only the document having >=2 banas
- Project only the necessary output
Option 2: ( Best , inspired by Buzz below 🙂 )
db.collection.aggregate([
{
$match: {
$expr: {
$gte: [
{
$size: {
$filter: {
input: "$fruits",
as: "item",
cond: {
$eq: [
"$$item",
"banana"
]
}
}
}
},
2
]
}
}
}
])
Explained:
Just match those having >=2 bananas , best if index created on fruits
( I think this solution is in 50/50 performance competition with the $reduce option from Buzz below )