是的,这是可能的。只需添加一个$group 阶段,_id 等于null。这将计算所有输入文档作为一个整体的累积值。例如
{ $group: { _id: null, total: { $sum: "$price" }}}
或者如果您只想从聚合结果中获取一个文档,您可以使用$limit:
{ $limit: 1 }
更新:这两种解决方案都返回 cursor ,它只有一个文档。但不要将findOne 视为特别的东西。它还检索光标并仅获取第一个文档(如果有)。这是findOne的mongo shell实现:
function ( query , fields, options ){
var cursor = this.find(query, fields, -1 /* limit */, 0 /* skip*/,
0 /* batchSize */, options);
if ( ! cursor.hasNext() )
return null;
var ret = cursor.next();
if ( cursor.hasNext() ) throw "findOne has more than 1 result!";
if ( ret.$err )
throw "error " + tojson( ret );
return ret;
}
如您所见,它在内部使用find。因此,如果您想获取单个文档而不是单个文档的光标,您可以编写自己的函数,该函数与 aggregate 相同。例如
> DBCollection.prototype.aggregateOne = function(pipeline) {
var cur = this.aggregate(pipeline);
if (!cur.hasNext())
return null;
return cur.next();
}
用法:
> db.collection.aggregateOne(...)