【问题标题】:Problemm using concat in array mongodb在数组 mongodb 中使用 concat 的问题
【发布时间】:2021-08-17 11:23:44
【问题描述】:

我有 3 张桌子

1) Actor: actor_id, first_name, last_name 
2) Film: film_id, title
3) Film_Actor: film_id, actor_id

示例文档:

_id
:
60aedac769985522a024daca
actor_id
:
"1"
first_name
:
"Penelope"
last_name
:
"Guiness"

我想要的结果不仅是 first_name,还有 last_name。我在$group 函数中使用concat 时遇到问题。 我的完整代码:

    db.film.aggregate([
  {
    $lookup: {
      from: "film_actor",
      localField: "film_id",
      foreignField: "film_id",
      as: "film_actor"
    }
  },
  {
    $lookup: {
      from: "actor",
      localField: "film_actor.actor_id", 
      foreignField: "actor_id",
      as: "actor"
    }
  },
  {
    $group: {
      _id: "$film_id",
      title: {"$first":"$title"},
      name: {$push: "$actor.first_name"}
                }
  }
]);

错误报告:

$concat only supports strings, not array

想要的输出:

id:"207"
title:"Dangerous Uptown"
name:Array
0:"Penelope Guiness"
1:"Mary Watson"
2:"Ralph Holts"
3:"Spencer Dani"

【问题讨论】:

  • 发布您收藏的示例文档。
  • 你能告诉我们你的样本数据是什么样子吗?
  • @turivishal 完成,我已编辑问题
  • @varman 完成,我已编辑问题
  • 请发布有效的 json 格式文档,我在您的文档中看不到 film_id 字段并且您已在 $group 中使用。

标签: arrays mongodb aggregation


【解决方案1】:

感谢您所做的,我已经对您的代码进行了一些更改

  • $lookup 加入收藏。我已经开始收藏 Flim 了
  • $unwind 解构数组
  • $group 重建我们已经解构的数组,这将
  • 由于我们有嵌套数组,我们需要使用 $map 循环遍历它们以收集名字和姓氏
  • 上述阶段将再次嵌套数组,因此我们使用$reduce再次循环并使用$setUnion删除内部数组

删除一些重复的条目,取决于您的要求

这里是代码

db.Film.aggregate([
  {
    $lookup: {
      from: "Film_Actor",
      localField: "film_id",
      foreignField: "film_id",
      as: "join_flim"
    }
  },
  { "$unwind": "$join_flim" },
  {
    $lookup: {
      from: "Actor",
      localField: "join_flim.actor_id",
      foreignField: "actor_id",
      as: "join_flim.join_actor"
    }
  },
  {
    $group: {
      _id: "$_id",
      title: { $first: "$title" },
      join_flim: { $push: "$join_flim" }
    }
  },
  {
    "$project": {
      title: 1,
      actornames: {
        $map: {
          input: "$join_flim",
          as: "f",
          in: {
            $map: {
              input: "$$f.join_actor",
              as: "a",
              in: {
                $concat: [ "$$a.first_name", " ", "$$a.last_name" ]
              }
            }
          }
        }
      }
    }
  },
  {
    "$project": {
      title: 1,
      actornames: {
        "$reduce": {
          "input": "$actornames",
          "initialValue": [],
          "in": {
            "$setUnion": [ "$$this", "$$value" ]
          }
        }
      }
    }
  }
])

工作Mongo playground

【讨论】:

  • 感谢您的解释。现在我很难面对 $unwind。我的代码:{ $unwind: "$join_flim"} 仍在报告:$unwind 阶段无法识别的选项:$unwind 如何解决这个问题?塔恩克斯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多