How can I get (Node.js) MongoDB documents with a distinct value where some other value is the lowest?

StackOverflow https://stackoverflow.com/questions/22676705

  •  22-06-2023
  •  | 
  •  

Frage

I have a collection like this:

{
    name : 'a',
    value: 10,
    word : 'baz'
},
{
    name : 'a',
    value: 65,
    word : 'bar'
},
{
    name : 'a',
    value: 3,
    word : 'foo'
},
{
    name : 'b',
    value: 110,
    word : 'bar'
},
{
    name : 'b',
    value: 256,
    word : 'baz'
}

How do I perform a query that results in selecting the full documents where name is unique, and value is the lowest? E.g.:

{
    name : 'a',
    value: 3,
    word : 'foo'
},
{
    name : 'b',
    value: 110,
    word : 'bar'
}
War es hilfreich?

Lösung

You could use the $min operator in the aggregation framework to achieve what you want using a query like:

db.collection.aggregate([
    {$group:{_id:"$name", value:{$min:"$value"}}}, 
    {$limit:2}
])

This query would return:

{
        "result" : [
                {
                        "_id" : "b",
                        "value" : 110
                },
                {
                        "_id" : "a",
                        "value" : 3
                }
        ],
        "ok" : 1
}

You can also include a $sort phase in the pipeline if you want your results to be sorted.

EDIT: You can select other elements not included in $group's _id field using a neat little trick. First sort the documents and then use the $first operator:

db.collection.aggregate([
    {$sort:{value:1}},
    {$group:{_id:"$name", value:{$min:"$value"}, word:{$first:"$word"}}} 
])

This query would return:

{
        "result" : [
                {
                        "_id" : "b",
                        "value" : 110,
                        "word" : "bar"
                },
                {
                        "_id" : "a",
                        "value" : 3,
                        "word" : "foo"
                }
        ],
        "ok" : 1
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top