check the conditions
- if the
value
is greater equal 1000. - if the
value
is less than equal 2000. from the parameters, the user will select either1
or2
. User get the output in the same structure but only those documents that fulfill the condition in MongoDB
{
"data": [
{
"value": 1000
},
{
"value": 3000
},
{
"value": 1500
}
]
}
CodePudding user response:
This query answers in the question :
- user enters 1 or 2 saved in a application variable lets say
var=parameter
- if he entered 1 => i want the documents that data.value>=1000
- if he entered 2 => i want the documents that data.value<=1000
*also assumes that data(in your sample data) is an array not a collection.
Query
- make
{"eq" : [1 ,1]}
to{"eq" : [parameter ,1]}
where parameter is your variable that has the value the user selected - works using a condition, if the user entered 1, first comparison is made or if user entered 2 , second comparison is made
- the comparison is done with the aggregate operators, the query operators when you compare an array(the auto take the min or max), but aggregate ones doesn't do auto, so its done here with the
$max
and$min
operators. Istead of searching for the number we find the max/min and we compare (like query operators auto-do)
db.collection.aggregate([
{
"$match": {
"$expr": {
"$cond": [
{
"$eq": [
1,
1
]
},
{
"$gte": [
{
"$max": "$data.value"
},
1000
]
},
{
"$lte": [
{
"$min": "$data.value"
},
2000
]
}
]
}
}
}
])