Return a document with the max value on a number field using MongoDB aggregation

浪子不回头ぞ 提交于 2019-12-24 12:34:05

问题


If I have a bunch of documents for instance

{
  _id: mongoId,
  subcatId: mongoId,
  viewCount: 2
}

_id is unique but subcatId isn't.

If I wanted to return each document that had the highest viewCount per subcatId, how would I do that using aggregation with Mongoose/MongoDB?


回答1:


You can do that like this:

db.test.aggregate([
  // Sort the docs by viewCount descending so that the highest ones come first
  {$sort: {viewCount: -1}},
  // Group by subcatId and take the first doc from each group
  {$group: {_id: '$subcatId', doc: {$first: '$$ROOT'}}}
])

The $$ROOT system variable was added in 2.6 and represents the whole document being processed at that stage in the pipeline. All system variables are referenced with the $$ prefix.

For older versions of MongoDB, you need to individually add each field you need to the $group:

db.test.aggregate([
  {$sort: {viewCount: -1}},
  {$group: {
    _id: '$subcatId', 
    doc_id: {$first: '$_id'},
    viewCount: {$first: '$viewCount'}
  }}
])


来源:https://stackoverflow.com/questions/26811178/return-a-document-with-the-max-value-on-a-number-field-using-mongodb-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!