2017-09-23 73 views
0

所以我还挺新Node.js的我不明白为什么总结查询不适合我。我已经在Mongo Shell上尝试了相同的查询,并且完美运行。 下面的代码:的Node.js:查询聚合不工作(MongoDB的)

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 

回答

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); 
}); 
+0

感谢您的帮助! – Barnes