【问题标题】:Get the size of an array of each document in a sub array获取子数组中每个文档的数组大小
【发布时间】:2016-10-11 21:12:40
【问题描述】:

我在“gyms”集合中有一个文档,如下所示:

 "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 的参数必须是数组,但类型为:字符串

查询:

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

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    最好和最有效的方法是使用$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"  
                        } 
                    } 
                } 
            }}
        ]
    )
    

    【讨论】:

    • 我认为在 mongo 中会有更简单的方法来做到这一点,显然不是。谢谢!
    • 更短的方法* 喜欢我的查询。
    猜你喜欢
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多