【问题标题】:Can the value of the key-value pair returned by aggregate operations in MongoDB be extracted?可以提取MongoDB中聚合操作返回的键值对的值吗?
【发布时间】:2021-07-27 16:20:37
【问题描述】:

这是一个试图获得最高品牌平均价格的代码。

var x = db.inventory.aggregate([
{$match:{'Origin':'USA'}},
{$group:{_id:'$Brand', top_avgprice:{$avg:'$Price'}}},
{$project: {_id:0,top_avgprice:1}},
{$sort: {top_avgprice:-1}},
{$limit:1}
])

打印 x 返回一个键值对,例如top_avgprice:10,000

但是当我尝试通过执行下面的代码来访问该值时,它什么也不返回。

x.top_avgprice

我如何单独退还那 10,000 个?稍后我将需要这个整数值用于另一个表达式。

【问题讨论】:

  • aggregate() 方法总是会产生数组,你可以试试x[0].top_avgprice

标签: mongodb nosql aggregation


【解决方案1】:

当您进行聚合时,它会返回带有光标的数据,因此您需要遍历它以访问如下数据:

var x = db.inventory.aggregate([
{$match:{'Origin':'USA'}},
{$group:{_id:'$Brand', top_avgprice:{$avg:'$Price'}}},
{$project: {_id:0,top_avgprice:1}},
{$sort: {top_avgprice:-1}},
{$limit:1}
]).toArray();

x.forEach(function(e) {
    print('e.top_avgprice: ', e.top_avgprice);

});

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2012-07-11
    相关资源
    最近更新 更多