获取子数组中每个文档的数组大小

时间:2016-06-10 19:47:14

标签: mongodb mongodb-query aggregation-framework

我在“健身房”系列​​中有一个文件,如下所示:

 "name" : "Testing",
 "albums" : [ 
    {
        "name" : "Aerobics",
        "photos" : [ 
            {
                "filepath" : "aerobics.jpg"
            }
        ]
    }, 
    {
        "name" : "Aqua",
        "photos" : [ 
            {
                "filepath" : "aqua.jpg"
            }
        ]
    }, 
    {
        "name" : "Zumba",
        "photos" : [ 
            {
                "filepath" : "zumba.jpg"
            }
        ]
    }
],

我想从每张专辑中选择投影中的照片数量。

所以我的输出如下所示:

 "name" : "Testing",
 "albums" : [ 
    {
        "name" : "Aerobics",
        "amount_photos" : 1,
        "photos" : [ 
            {
                "filepath" : "aerobics.jpg"
            }
        ]
    }, 
    {
        "name" : "Aqua",
        "amount_photos" : 1,
        "photos" : [ 
            {
                "filepath" : "aqua.jpg"
            }
        ]
    }, 
    {
        "name" : "Zumba",
        "amount_photos" : 1,
        "photos" : [ 
            {
                "filepath" : "zumba.jpg"
            }
        ]
    }
]

它应该可以通过聚合实现,但是当我尝试查询时出现以下错误:

  

$ size的参数必须是一个数组,但类型为:String

查询:

 db.gyms.aggregate(
   [
      {
         $project: {
            'albums.photos' : {
               amountPhotos: { $size: "photos" } 
            }
         }
      }
   ]
)

1 个答案:

答案 0 :(得分:2)

执行此操作的最佳和最有效的方法是使用$map运算符,该运算符允许您使用{"照片"的$size返回子文档数组。阵列。

db.gyms.aggregate( 
    [ 
        { "$project": { 
            "name": 1, 
            "albums": { 
                "$map": { 
                    "input": "$albums", 
                    "as": "album", 
                    "in": { 
                        "amount_photos": { "$size": "$$album.photos" },
                        "name": "$$album.name", 
                        "photos": "$$album.photos"  
                    } 
                } 
            } 
        }}
    ]
)