mongodb - 演员的 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"
}
}
我怎么解决这个问题?提前致谢。
解决方案
展平数组后,您可能需要$unwind
在阵列上再做一次,然后按两个字段(即演员和类别字段)对所有展平的文档进行分组,以创建电影标题列表。categories
actors
需要另一个组来塑造结果字段。
以下管道应为您提供所需的结果:
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" }
} }
])
推荐阅读
- debugging - 我如何判断 Windows (PE) 可执行文件是否具有调试符号?
- python - 如何在python中隐藏标签直到按下按钮
- node.js - 为什么 server.listen(0) 返回另一个应用程序正在侦听的端口?
- c++ - 尽管定义了除信号之外的所有函数,但在 qt 中未定义对 vtable 的引用?
- coffeescript - Atom-Editor:无法加载 init.coffee - 错误:保留字“功能”
- sql - 使用左连接时无法启用复合索引
- c# - ASP.net Core Web API - 正确的招摇注释
- python - 使用 pandas 将 BLOB 存储中的 .xlsx 转换为 .csv,无需下载到本地计算机
- python - 如何使用 Python 中的多处理管理器使用来自另一个进程的变量更新 matplotlib.Funcanimation 中的数据?
- rest - 如何从比赛共享代码下载 CS:GO 演示