MongoDB 中聚合方法的返回类型是什么? [英] What is the return type of aggregate method in MongoDB?

查看:37
本文介绍了MongoDB 中聚合方法的返回类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据 mongo 的聚合方法获得一组结果,并根据返回我试图在所有结果中添加一个属性.聚合方法为我提供了最高的编号.一个月内某个综合体中特定商店的销售额.我想向它返回的那些文档添加一个属性highestSales.我的查询是:

I am trying to get a set of results based on the aggregate method of mongo and based on the return I am trying to add a property in all of them. The aggregate method provides me the highest no. of sales in a month from a particular outlet in a complex. I want to add a property highestSales to those documents which it returns. My query is:

var shops = db.data.aggregate([
    {
        $group: {
            _id: "$shopName",
            Sales: { $max: "$Sales" } 
        }
    }
]);

shops 变量为我提供了 5 个商店名称,如下所示:

The shops variable provides me 5 shop names as below:

{ "_id" : "Shop1", "Sales" : "$83,000" }
{ "_id" : "Shop2", "Sales" : "$69,000" }..

但是当我试图在商店中循环时,它不允许我添加新属性.我假设的原因是商店不是一组对象.任何人都可以告知相同的返回类型是什么??这可以通过任何其他方式实现吗?

But when I am trying to loop through the shops it is not allowing me to add a new property. The reason I assume is that the shops is not an array of objects. Can anyone kindly inform what is the return type of the same?? Can this be achieved in any other way?

推荐答案

aggregate() 方法返回一个游标到聚合管道操作的最后阶段产生的文档,或者如果你包含了解释选项,文档它提供了有关聚合操作处理的详细信息.

aggregate() method returns a cursor to the documents produced by the final stage of the aggregation pipeline operation, or if you include the explain option, the document that provides details on the processing of the aggregation operation.

您需要添加一个toArray() 方法到商店变量或 aggregate() 方法的结果光标,例如

You need to add a toArray() method to the shops variable or the resulting cursor from the aggregate() method, e.g.

var shops = db.data.aggregate([
    {
        $group: {
            _id: "$shopName",
            Sales: { $max: "$Sales" } 
        }
    }
]).toArray();

toArray() 方法返回一个包含游标中所有文档的数组.该方法对游标进行完全迭代,将所有文档加载到RAM中并耗尽游标.

The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.

这篇关于MongoDB 中聚合方法的返回类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆