问题
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