2012-12-03 37 views
0

在通過集合框架管道化各種文檔後,我終於得到了生成的文檔。

現在的問題是,我只想要$ first和$ last文檔。

最後文件看起來像這樣(巨大的名單):

  ... 
      { 
        "_id" : "Kaila Deibler", 
        "count" : 406 
      }, 
      { 
        "_id" : "Jessika Dagenais", 
        "count" : 406 
      }, 
      { 
        "_id" : "Tamika Schildgen", 
        "count" : 404 
      }, 
      ... 

的,我用來製作文檔蒙戈shell命令是:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}])

但我只需要第一個和最後一個所以我試圖這樣的事情:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$first: "$_id"}])

我試過其他的實現,但似乎無法無花果排除何時/在哪裏執行$first$last

有什麼建議嗎?

回答

0

這是我自己回答這個問題的例子:

db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$group: {_id: "$_id.comments.author", first: {$first: "$_id"}, last: {$last: "_id"}}}])

因爲我想拉排序後的第一個和最後一個文件,我必須將另一個$group$first$last。其結果是:

{ 
     "result" : [ 
       { 
         "_id" : null, 
         "first" : "Elizabet Kleine", 
         "last" : "Mariela Sherer" 
       } 
     ], 
     "ok" : 1 
} 

注意"_id" : null。這是必要的嗎?
如果有人有更好的解決方案,請分享。

+0

你想在結果的「_id」字段中出現什麼?看起來你正試圖再次顯示「comments.author」(現在它將出現在$ _id中)字段),但在上下文中沒有多大意義,你可以給它一個任意的名字,比如'{$ group:{_id:「First_and_Last」,...' –

+0

對,我忘了你可以這麼做。謝謝! – user1460015

1

$first$last$group管道中的聚合函數,這意味着您需要在$group文檔中使用它們。

db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}, first: {$first:"$_id"}}}, {$sort: {count: -1}}]) 

同樣,對於$last

可以發現,顯示了這個here

+0

我必須在第一個'$ group'之後排序,因爲我只想要最高和最低的計數。你有它的方式返回如下:'{「_id」:「Tawana Oberg」,「count」:396,「first」:Tawana berg「},{」_id「:」Mariela Sherer「,」count「: 387,「first」:「Mariela Sherer」}'。請注意,第一個只是'_id'的重複。 – user1460015

+0

我正要在'$ sort'之後建議你'$ group',但看起來你有 –

相關問題