首页 > 解决方案 > 演员的 mognodb 聚合组

问题描述

我有以下电影收藏结构:

{
   "_id" : ObjectId,
   "title" : "movie-1",
   "actors" : [
      "actor-1",
      "actor-2",
      "actor-3",
   ],
   "categories" : [
     "category-1",
     "category-2"
   ]
 }

我想显示所有演员与相关电影和类别的结果,如下所示:

{
    "actor": "actor-1",
    "result": {
        "category-1": [ "movie-1", "movie-2" ],
        "category-2": [ "movie-1", "movie-4" ]
    }
}

我尝试过如下聚合:

db.film.aggregate([
   {  $unwind: "$actors"  },
   {  $group: { 
        _id: "$actors", 
        data: {  $push: {  movie: "$title",   categories: "$categories"  } }
      }
   }, 
   {
      $project: {
        _id: 0,
        actor: "$_id",
        result: {
          $reduce: {
             input: "$data",
             initialValue: {},
             in: {
               $let: {
                  vars: { movie: "$$this.movie", categories: "$$this.categories" },
                  in: {
                     $arrayToObject: {
                         $map: {
                           input: "$$categories",
                           in: { k: "$$this",  v: "$$movie" }
                         }
                      }
                  }
               }
             }
           }
        }
      }
    }
 ])

但是我得到了所有演员列表,其中只有一部电影的类别如下所示:

{
   "actor" : "actor-1",
   "result" : {
     "category-1" : "movie-1",
     "category-2" : "movie-2",
     "category-3" : "movie-3"
   }
}

我怎么解决这个问题?提前致谢。

标签: mongodbaggregation-framework

解决方案


展平数组后,您可能需要$unwind在阵列上再做一次,然后按两个字段(即演员和类别字段)对所有展平的文档进行分组,以创建电影标题列表。categoriesactors

需要另一个组来塑造结果字段。

以下管道应为您提供所需的结果:

db.film.aggregate([
    { "$unwind": "$actors" },
    { "$unwind": "$categories" },
    { "$group": { 
        "_id": { "actor": "$actors", "category": "$categories" },
        "movies": { "$push": "$title" }
    } },
    { "$group": { 
        "_id": "$_id.actor",
        "result": { 
            "$push": {
                "k": "$_id.category",
                "v": "$movies"
            }   
        }
    } },
    { "$addFields": {
       "result": { "$arrayToObject": "$result" }  
    } }
])

推荐阅读