【问题标题】:Node.js: Query Aggregation not working (mongodb)Node.js:查询聚合不起作用(mongodb)
【发布时间】:2017-09-23 14:43:57
【问题描述】:

所以我对 node.js 有点陌生。而且我不明白为什么聚合查询对我不起作用。我在 Mongo Shell 上尝试过相同的查询,它运行良好。 代码如下:

db.collection("companies").aggregate({$match:
{$or:
    [{ $and:
        [{ left: {$gt: 2}}, {left: {$lt: 11}}]},
    { $and:
        [{ right: {$gt: 2}}, {right: {$lt: 11}}]}]}},
{ $group:
    {_id:null, 
        Sum:{$sum: "$earn"}}}, 

function(err, data){

    if (err) throw err;

    console.log(data[0]);
    console.log(data.value);
    console.log(data.Sum);
});

控制台输出:

undefined
undefined
undefined

【问题讨论】:

    标签: javascript node.js mongodb aggregation-framework


    【解决方案1】:

    聚合参数需要是一个数组,因为聚合适用于管道概念,其中最后一个管道的输出将成为当前管道的输入。

    db.collection("companies").aggregate([
    {$match:
      {$or:
          [{ $and:
              [{ left: {$gt: 2}}, {left: {$lt: 11}}]},
          { $and:
              [{ right: {$gt: 2}}, {right: {$lt: 11}}]}]
    }},
    { $group:
        {_id:null, 
            Sum:{$sum: "$earn"}}}], 
    
    function(err, data){
    
        if (err) throw err;
    
        console.log(data[0]);
        console.log(data.value);
        console.log(data.Sum);
    });
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2019-06-18
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多