1

Suppose I have the following documents:

{
"name":"Matheus",
"age: 29"
},
{
"name":"Nicolas",
"age: 28"
},
{
"name":"Raphael",
"age: 26"
},
{
"name":"Trump",
"age: 48"
},
{
"name":"Elon Musk",
"age: 35"
}

Now, suppose I want to retrieve the document with the greatest age, but up to a given age, like this: return document with the greatest age up to 36, this should return

"name":"Elon Musk",
"age: 35"
}

Note that the less or equal operator wouldn't work, because I don't need the greatest of all, I need the greatest up to a certain number. I've learned here that I can acomplish almost what I want by doing

db.collection.find().sort({age:-1}).limit(1) // for MAX

but I don't need the global max, just the max inside a given bound. How can I acomplish this?

Community
  • 1
  • 1
Gatonito
  • 1,662
  • 5
  • 26
  • 55

3 Answers3

1
db.collection.find({age:{$lte:36, $gte:20}}).sort({age:-1}).limit(1)
Siva Kumar
  • 164
  • 1
  • 2
  • 9
0

Just pass the filter condition on the find and the it will retrieve the local maximum. db.collection.find({age: {$lt:36}}).sort({age:-1}).limit(1).

Shibasis Patel
  • 315
  • 2
  • 14
-1

If you are looking for a query which performs operation on a range, then this would help

Let us have a collection named stackoverflow with below records

db.stackoverflow.find();
{ "_id" : ObjectId("5792c958caada3861f12e724"), "name" : "Matheus", "age" : 29 }
{ "_id" : ObjectId("5792c958caada3861f12e725"), "name" : "Nicolas", "age" : 28 }
{ "_id" : ObjectId("5792c958caada3861f12e726"), "name" : "Raphael", "age" : 26 }
{ "_id" : ObjectId("5792c958caada3861f12e727"), "name" : "Trump", "age" : 48 }
{ "_id" : ObjectId("5792c95acaada3861f12e728"), "name" : "Elon Musk", "age" : 35 }

the max of the set from [-a, 36] where a is any positive real number

Now let us assume a=28, then the query to retrieve records which are having age greater than 28 and less than 36 is shown below

db.stackoverflow.find({age:{$gt: 28, $lt:36}});

and execution of this query would show the below result

{ "_id" : ObjectId("5792c958caada3861f12e724"), "name" : "Matheus", "age" : 29 }
{ "_id" : ObjectId("5792c95acaada3861f12e728"), "name" : "Elon Musk", "age" : 35 }
Clement Amarnath
  • 5,301
  • 1
  • 21
  • 34