我在“健身房”系列中有一个文件,如下所示:
"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" }
}
}
}
]
)
答案 0 :(得分:2)