Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB find and return all with max value

I'm trying to get a list of documents that have the max value. I can specify it if I know the number of documents with max value (like in the solution in this another stackoverflow solution 'mongodb how to get max value from collections'), but I don't know how to do it if I don't know what the number of documents is.

For example, using the following documents:

{name:"a", age:10}
{name:"b", age:11}
{name:"d", age:12}
{name:"c", age:12}

So I know that there are 2 documents with max age of 12. Therefore I can write the following query

db.collection.find().sort({age: -1).limit(2)

I use limit(2) because I know that there are 2 documents with a max value, but how can I automate that? Can I count the records with max value, store it in a variable and use it like limit(n)? Is there any other way to do it?

like image 554
Selrac Avatar asked Jun 02 '16 20:06

Selrac


People also ask

Is there a $in in MongoDB?

For comparison of different BSON type values, see the specified BSON comparison order. If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (for example, <value1> , <value2> , and so on).

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do I use $in in MongoDB?

MongoDB provides different types of comparison query operators and $in operator is one of them. This operator is used to select those documents where the value of the field is equal to any of the given value in the array.

What is $first in MongoDB?

This means $first returns the first order type for the documents between the beginning of the partition and the current document.


1 Answers

you can use aggregation framework to get results

var group = {$group:{_id:"$age", names:{$push:"$name"}, count:{$sum:1}}}
var sort = {$sort:{"_id":-1}}
var limit= {$limit:1}
db.selrac.aggregate([group, sort, limit])

and output looks like this:

{
    "_id" : 12.0,
    "names" : [ 
        "d", 
        "c"
    ],
    "count" : 2.0
}

or if there is a need to have full document reference replace group by this:

var group = {$group:{_id:"$age", fullDocument:{$push:"$$ROOT"}, count:{$sum:1}}}

output:

{
    "_id" : 12.0,
    "fullDocument" : [ 
        {
            "_id" : ObjectId("57509a890d4ae20f6de06657"),
            "name" : "d",
            "age" : 12.0
        }, 
        {
            "_id" : ObjectId("57509a890d4ae20f6de06658"),
            "name" : "c",
            "age" : 12.0
        }
    ],
    "count" : 2.0
}

Any comments welcome!

like image 135
profesor79 Avatar answered Oct 10 '22 04:10

profesor79