使用MongoDB聚合返回数字字段上具有最大值的文档 [英] Return a document with the max value on a number field using MongoDB aggregation
本文介绍了使用MongoDB聚合返回数字字段上具有最大值的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果我有一堆文件
If I have a bunch of documents for instance
{
_id: mongoId,
subcatId: mongoId,
viewCount: 2
}
_id
是唯一的,但subcatId
不是唯一的.
_id
is unique but subcatId
isn't.
如果我想返回每个subcatId的viewCount最高的每个文档,我该如何使用Mongoose/MongoDB的聚合功能呢?
If I wanted to return each document that had the highest viewCount per subcatId, how would I do that using aggregation with Mongoose/MongoDB?
推荐答案
您可以这样做:
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'}}}
])
$$ROOT
系统变量已添加到2.6,表示管道中该阶段正在处理的整个文档.所有系统变量都以$$
前缀引用.
对于较旧的MongoDB版本,您需要分别将所需的每个字段添加到$group
:
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'}
}}
])
这篇关于使用MongoDB聚合返回数字字段上具有最大值的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文