2017-03-14 30 views
0

你好我看了文档:https://docs.mongodb.com/manual/reference/operator/aggregation/size/ 从我读的,如果我有一个作者属性的对象,它里面我有多个作者又名数组我应该使用内部大小聚集但是我得到一个错误:mongodb数组大小聚集大小失败

如果我打db.posts.find()漂亮()我得到这样的:

{ 
 
\t "_id" : ObjectId("58c7e35a8a00f209be819771"), 
 
\t "allReviewsLink" : "link somewhere", 
 
\t "totalReviewCount" : "200" 
 
} 
 
{ 
 
    \t "_id" : ObjectId("58c7e515be41d40a39954a38"), 
 
    \t "authors" : [ 
 
    \t \t "Linda", 
 
    \t \t "Benn", 
 
    \t \t "Carolyn" 
 
    \t ] 
 
    }

而这就是余吨里德没有成功:

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

哪里的帖子是我收集,我得到以下错误:语法错误:丢失:后属性ID @(壳):1:63

+0

在'$ project'阶段使用'$ size'运算符。就像'db.posts.aggregate([{$ project:{size:{$ size:“$ authors”}}}])' – Veeram

+0

我不相信你需要在'authors'之类的属性前面需要''''' – JLewkovich

+0

我编辑了我的问题,也许它有助于澄清。 – Defoe

回答

1

你可以通过几种方法来做到这一点。

这个查询将不存在authors值设置为一个大小为0

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

或者你也可以筛选使用$match第一,然后计算尺寸的文档。

db.posts.aggregate([ {$match:{authors:{$exists:true}}},{$project:{ size: {$size:"$authors" }}} ]) 
0

使用$项目汇总,

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

我得到这个错误:错误:命令失败:{..... – Defoe

+0

我编辑了我的问题,也许它有助于澄清。 – Defoe

+0

上面的命令应该返回大小:3,你的预期输出是什么? – radhakrishnan