【发布时间】:2017-03-14 13:34:19
【问题描述】:
您好,我查看了文档:https://docs.mongodb.com/manual/reference/operator/aggregation/size/ 从我读到的内容来看,如果我有一个带有 authors 属性的对象,并且在其中我有多个作者 a.k.a 数组,我应该在聚合中使用 size 但我得到一个错误:
如果我点击 db.posts.find().pretty() 我会得到:
{
"_id" : ObjectId("58c7e35a8a00f209be819771"),
"allReviewsLink" : "link somewhere",
"totalReviewCount" : "200"
}
{
"_id" : ObjectId("58c7e515be41d40a39954a38"),
"authors" : [
"Linda",
"Benn",
"Carolyn"
]
}
这就是我尝试但没有成功的方法:
db.posts.aggregate( [ {$size: {"$authors" } } ] )
posts 是我的收藏,我收到以下错误:SyntaxError: missing : after property id @(shell):1:63
【问题讨论】:
-
将
$size运算符与$project阶段一起使用。类似db.posts.aggregate( [ {$project:{ size: {$size: "$authors" }}} ] ) -
我认为您不需要在
authors等属性前面使用$ -
我编辑了我的问题,也许有助于澄清。
-
使用
db.posts.aggregate( [ {$project:{ size: {$size: {$ifNull:["$authors", []] }}}} ] )容纳不存在的字段。或者,您也可以使用$match在$project阶段之前过滤这些文档 -
是的!!!这是答案伙伴。请回答它,以便我验证它;)
标签: mongodb aggregation-framework