首页 > 解决方案 > Get maximum value for a field, but only with respect to other documents with the same value in another field

问题描述

I have mongodb documents like this:

{'device':'A','value':12}
{'device':'A','value':13}
{'device':'A','value':14}
{'device':'B','value':4}
{'device':'B','value':5}

I would like to find

{'device':'A','value':14}
{'device':'B','value':5}

i.e. for each device (here A and B) the documents with the highest value.

What I am doing so far is to find all the distinct devices in one query and then get all the documents for each device individually sorted descending with a limit of 1. But this needs lots of queries.

Is there a way to do this in one query?

标签: mongodbmongodb-queryaggregation-framework

解决方案


You need to use $group aggregation operator with $max accumulator.

db.collection.aggregate([
  { "$group": {
    "_id": "$device",
    "value": {
      "$max": "$value"
    }
  }},
  { "$project": { "_id": 0, "value": 1, "device": "$_id" }}
])

MongoPlayground


推荐阅读