2017-11-25 180 views
0

我有一个MongoDB的集合,一个文件如 -MongoDB的聚集查询 - 集团合计字段错误

{ 
    "_id" : ObjectId("5a187babdbf0a03cdca0d0bc"), 
    "aggregationDate" : "2017-10-31", 
    "ipaddress" : "10.65.66.184", 
    "first" : { 
     "count" : 3 
    }, 
    "second" : { 
     "count" : 2 
    }, 
    "third" : { 
     "count" : 3 
    }, 
} 

大约有30000这样的文件,与每天产生约1000个新的。我想显示具有最高活动性的“ipaddress”,它被定义为“first”,“second”和“third”的最高计数。

我抬头聚集查询并写了下面的一个 -

db.collection.aggregate({ $group : { ipaddress: "$ipaddress", 
          max: { $max : [ "$first.count", "$second.count", "$third.count" }}}); 

可惜我得到一个错误 -

"errmsg" : "exception: the group aggregate field 'ipaddress' must be defined as an expression inside an object", 

是否有人可以帮助我这个错误,并与写作聚集查询为我的要求?由于

+0

你在寻找最高的第一和第二和第三或第一,第二和第三的最高总和?例如。具有{第一:10,第二:10,第三:10}的文档可以具有最高的所有个体,但是{第一:200,第二:0,第三:0}在所述字段中具有更高的总和。 –

+0

@BuzzMoschetti第一,第二和第三的最高总和是我在寻找的 –

回答

0

这应该做的伎俩。您也需要$add功能。

db.foo.aggregate([ 
    {$group: {_id: "$ipaddress", 
      max: { $max: {$add: [ "$first.count", "$second.count", "$third.count"] } } 
      } 
    } 
]); 
+0

啊,是的!非常感谢.. :) –

0

是啊,那是因为在$group管道不能有这样的事情

ipaddress: "$ipaddress" 

领域ip地址必须由蓄电池操作员陪同。这里的文档是优秀看看here

如果你的意思是按ip地址,那么你必须把它写这样的:

_id: "$ipaddress" 

$max运营商不会以这种方式工作要么。这是您在$project管道中使用它的方式,而不是在$group中。请看一看here

所以,你的聚集将有看起来像这样:

db.collection.aggregate([ 
{ 
    $group: 
    { 
     _id: "$ipaddress", 
     max: { 
      $max: {first: "$first.count", second: "$second.count", third: "$third.count"} 
     } 
    } 
} 
])