2017-11-25 177 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"} 
     } 
    } 
} 
])