I Have tried using the $all operator and the $and operator and still can't make any progress
I want to only return the documents that every item in the ratings array is greater than 8 and less than 10
Here are my example documents:
This is the query I am trying to run:
db.Practicelab2.find({ratings: {$elemMatch:{$gt:8, $lt:10}}})
{ _id: ObjectId("6331c8407a386c3c9bd9f976"),
title: 'The Last Student Returns',
meta: { rating: 9.5, aired: 2018, runtime: 100 },
visitors: 1300000,
expectedVisitors: 1550000,
genre: [ 'thriller', 'drama', 'action' ],
ratings: [ 10, 9 ] }
{ _id: ObjectId("6331c8407a386c3c9bd9f977"),
title: 'Supercharged Teaching',
meta: { rating: 9.3, aired: 2016, runtime: 60 },
visitors: 370000,
expectedVisitors: 1000000,
genre: [ 'thriller', 'action' ],
ratings: [ 10, 9, 9 ] }
CodePudding user response:
You can chain up $allElementsTrue
and $map
with your conditions. The idea is to create a boolean array with $map
. Use $allElementsTrue
on the resulting boolean array to perform the filtering.
db.collection.find({
$expr: {
$eq: [
true,
{
"$allElementsTrue": {
"$map": {
"input": "$ratings",
"as": "r",
"in": {
$and: [
{
$gt: [
"$$r",
8
]
},
{
$lt: [
"$$r",
10
]
}
]
}
}
}
}
]
}
})
Here is the Mongo playground for your reference.