How can I get the document with the maximum value in one of my Mongo Db fields
Can anyone tell me how I can get the document with the maximum value in one of my Mongo Db.Using mongoTemplate Class fields
here is an example
{
"_id" : "post 1",
"author" : "Bob",
"content" : "...",
"page_views" : 5
}
{
"_id" : "post 2",
"author" : "Bob",
"content" : "...",
"page_views" : 9
}
{
"_id" : "post 3",
"author" : "Bob",
"content" : "...",
"page_views" : 8
}
so i want to get the following result
{
"_id" : "post 2",
"author" : "Bob",
"content" : "...",
"page_views" : 9
}
Recording with max page_views
+3
source to share
1 answer
This will be your mongoDB request, hopefully you can implement it in your driver
db.<collection name>.find({}).sort({'page_views':-1}).limit(1);
You will get an array of length one containing the requested document. -1
indicates sorting in descending order. limit(1)
limits the number of documents to 1. This way you get the document containing the largest number page_views
.
+5
source to share