mongodb - Get the size of an array of each document in a sub array -
i've document in collection 'gyms' looks following:
"name" : "testing", "albums" : [ { "name" : "aerobics", "photos" : [ { "filepath" : "aerobics.jpg" } ] }, { "name" : "aqua", "photos" : [ { "filepath" : "aqua.jpg" } ] }, { "name" : "zumba", "photos" : [ { "filepath" : "zumba.jpg" } ] } ],
i'd select amount of photos each album projection.
so output following:
"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" } ] } ]
it should achievable aggregation i'm getting following error when try query:
the argument $size must array, of type: string
query:
db.gyms.aggregate( [ { $project: { 'albums.photos' : { amountphotos: { $size: "photos" } } } } ] )
the best , efficient way using $map
operator allows return array of sub-documents $size
of "photos" array.
db.gyms.aggregate( [ { "$project": { "name": 1, "albums": { "$map": { "input": "$albums", "as": "album", "in": { "amount_photos": { "$size": "$$album.photos" }, "name": "$$album.name", "photos": "$$album.photos" } } } }} ] )
Comments
Post a Comment