MongoDB group by values in an array field

若如初见. 提交于 2019-12-18 06:59:49

问题


I have my asset documents in the below format.

db.asset.find({}).limit(1).pretty()
{
    "_id" : ObjectId("54e650a10364a65f62c0df4a"),
    "_class" : "com.model.core.Asset",
    "displayName" : "Bingo Rhymes For Children + More 3D Animation Nursery Rhymes & Kids' Songs",
    "assetType" : "VIDEO",
    "active" : true,
    "originalUrl" : "https://www.youtube.com/watch?v=j-tdVvvXn9k&feature=youtube_gdata",
    "groupIds" : [ ],
    "folderIds" : [
        "54e6507b0364a65f62c0df47",
        "54e6507b0364a65f62c0df48"
    ]
}

As you can see each asset can have a collection of folderId to which it is associated with. If I want to find the folderIds along with the associated assets how does the mongo aggregate query will look like? Essentially I want to group the assets by folderId.


回答1:


You first need to unwind by the folderIds field, than group by _id and push the asset _id into a list assets_id.

db.asset.aggregate([{$unwind:"$folderIds"},  {$group:{_id: "$folderIds",assets:{$push: {assets_id:"$_id"}}}}])


来源:https://stackoverflow.com/questions/33134523/mongodb-group-by-values-in-an-array-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!