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
}