简体   繁体   中英

How do you compute max and unique in Mongo?

I have a bunch of documents:

{ "name" : "A", "value" : 10},
{ "name" : "B", "value" : 12},
{ "name" : "B", "value" : 14},
{ "name" : "A", "value" : 16},
{ "name" : "C", "value" : 11}

I want to find the minimum value for each name, so the result would be

{ "name" : "A", "value" : 10},
{ "name" : "B", "value" : 12},
{ "name" : "C", "value" : 11}

What is the correct way to do this query in Mongo? I keep thinking in terms of SQL.

For the minimum, you can do this by using Mongo's Aggregation Framework with " $group " and "$min". Assuming that you had a collection named "myCollection," you could try something like this:

db.myCollection.aggregate({$group:{_id:"$name", minimumValue: {$min : "$value"}}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM