2017-03-24 25 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