【问题标题】:Double array $lookup call preserving original structure双数组 $lookup 调用保留原始结构
【发布时间】:2023-02-24 09:53:27
【问题描述】:

我正在尝试填充一个双数组对象,但在聚合中,所以我正在使用 $lookup 函数。该集合看起来像这样:

{
  foo: [
    {
      bar: [
        {
          _id: ObjectId('63f508eedd2962118c37ea36')
        }
      ]
    }
  ]
}

我的查找看起来像:

{
  $lookup: {
    from: "collection",
    localField: "foo.bar",
    foreignField: "_id",
    as: "foo.bar",
  },
}

这导致

{
  foo: {
    bar: [
      {
        _id: ObjectId('63f508eedd2962118c37ea36'),
        field1: "helloworld"
      }
    ]
  }
}

我真正想要的是

{
  foo: [
    {
      bar: [
        {
          _id: ObjectId('63f508eedd2962118c37ea36'),
          field1: "helloworld"
        }
      ]
    }
  ]
}

关于如何总体上实现我想要的任何想法?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    似乎是直接映射$lookup 用于嵌套数组是不可能的。

    1. $lookup - 加入collection 集合并返回bars 数组字段。

    2. $set - 设置foo 数组。

      2.1. $map - 迭代foo 数组中的元素。

      2.1.1. $mergeObjects - 将当前迭代的 foo 元素与结果合并2.1.1.1.

      2.1.1.1。带有 bar 字段的文档,其中包含的结果2.1.1.1.1.

      2.1.1.1.1。 $map - 迭代bar 数组中的元素。

      2.1.1.1.1.1。 $mergeObjects - 将当前迭代的bar 元素与bars 数组中的第一个匹配元素合并。

    3. $unset - 删除bars 数组。

      db.from.aggregate([
        {
          $lookup: {
            from: "collection",
            localField: "foo.bar._id",
            foreignField: "_id",
            as: "bars"
          }
        },
        {
          $set: {
            foo: {
              $map: {
                input: "$foo",
                as: "foo",
                in: {
                  $mergeObjects: [
                    "$$foo",
                    {
                      bar: {
                        $map: {
                          input: "$$foo.bar",
                          as: "bar",
                          in: {
                            $mergeObjects: [
                              "$$bar",
                              {
                                $first: {
                                  $filter: {
                                    input: "$bars",
                                    cond: {
                                      $eq: [
                                        "$$bar._id",
                                        "$$this._id"
                                      ]
                                    }
                                  }
                                }
                              }
                            ]
                          }
                        }
                      }
                    }
                  ]
                }
              }
            }
          }
        },
        {
          $unset: "bars"
        }
      ])
      

      Demo @ Mongo Playground

    【讨论】:

    • 哇,这是一个疯狂的聚合。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多