2017-03-24 24 views
0

你好,我在MongoDB中一個帖子集合,其中有一個作者字段,當我運行以下命令:MongoDB的項目計數與條件對象

db.posts.aggregate([ {$project:{ size: {$size: {$ifNull:["$authors", []] }}}} ])

我得到的結果這樣的:

{ "_id" : ObjectId("58c917fe48ad625ee8f49714"), "size" : 30 } 
 
{ "_id" : ObjectId("58c91b83895efc5f0f67ba1a"), "size" : 0 } 
 
{ "_id" : ObjectId("58c91cfd2971c05f310fccb8"), "size" : 30 } 
 
{ "_id" : ObjectId("58c91eb7a826965f85571656"), "size" : 30 } 
 
{ "_id" : ObjectId("58c921a1cb2bc85fa77e593a"), "size" : 30 }

如何計算大小不等於0時的次數? 所以在這種情況下,結果將是4.

我試過「db.posts.aggregate([{$ project:{size:{$ size:{$ not:{」$ authors「:0}}} }}]) 「沒有成功......

+0

你可以使用普通的查詢。 'db.posts.count({「authors」:{$ exists:true,$ ne:[]}})' – Veeram

+0

這個好友 – Defoe

回答

0

您想要使用$ match和$ count聚合方法,如下所示。查看更多MongoDB Aggregate $count

db.posts.aggregate( 
    [ { 
    $match:{ size: {$gt: 0}} 
    }, { 
    $count:'total' 
    } ]) 

這應該返回類似:

{ "total" : 4 } 
+0

我沒有收到任何東西,作者的字段在哪裏? – Defoe

+0

假設你有一定的AuthorID的數據結構,你可以這樣做: db.posts.aggregate( [{$ 匹配:{大小:{$ GT:0}} },{$ 組:{ _id:'$ authorId' },{ $ count:'total' }]) 然後它將通過authorId對結果進行分組。如果你想要整個post對象與聚合返回,你將不得不做一些不同的事情。我不知道你的數據是什麼樣的,所以你將不得不弄清楚如何讓這個例子適合你的數據。 –

+0

不,這不起作用,我不想按ID分組 – Defoe