【问题标题】:Mongodb lookup for array of ids with nested array of objects in other collectionMongodb在其他集合中查找具有嵌套对象数组的ID数组
【发布时间】:2022-02-22 16:34:42
【问题描述】:

我是 mongo db 的新手,我正在尝试查找两个集合的查找

一个集合是具有类似标签的用户

{
  _id: "fdkjkjs",
  first_name: "",
  last_name: "",
  role: "admin",
  tags:
    [
      { _id: "tag_1_id", name: "Tag 1" },
      { _id: "tag_2_id", name: "Tag 2" },
      { _id: "tag_3_id", name: "Tag 3" },
      { _id: "tag_4_id", name: "Tag 4" }
    ]
}

一个帖子集合如下

{
  _id: "fdkjkjs",
  title: "",
  slug: "",
  tags: ["tag_1_id", tag_3_id]
}

所以我想用用户集合中的名称获取帖子列表 API 中的所有标签。

所以我想要的结果是这样的

[{
  _id: "fdkjkjs",
  title: "",
  slug: "",
  tags: ["tag_1_id", tag_3_id],
  selectedTags: [
    { _id: "tag_1_id", name: "Tag 1" },
    { _id: "tag_3_id", name: "Tag 3" }
  ],
}]

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    方法一

    db.posts.aggregate([
      {
        "$lookup": {
          "from": "users",
          "localField": "tags",
          "foreignField": "tags._id",
          "as": "selectedTags"
        }
      },
      {
        "$set": {
          "selectedTags": {
            "$filter": {
              "input": { "$first": "$selectedTags.tags" },
              "as": "item",
              "cond": { $in: [ "$$item._id", "$tags" ] }
            }
          }
        }
      }
    ])
    

    mongoplayground


    方法二

    db.posts.aggregate([
      {
        $lookup: {
          from: "users",
          let: { tags_post: "$tags" },
          pipeline: [
            {
              "$unwind": "$tags"
            },
            {
              $match: {
                $expr: {
                  $in: [ "$tags._id", "$$tags_post" ]
                }
              }
            },
            {
              "$replaceWith": "$tags"
            }
          ],
          as: "selectedTags"
        }
      }
    ])
    

    mongoplayground


    方法3

    db.posts.aggregate([
      {
        $lookup: {
          from: "users",
          localField: "tags",
          foreignField: "tags._id",
          let: { tags_post: "$tags" },
          pipeline: [
            {
              "$unwind": "$tags"
            },
            {
              $match: {
                $expr: {
                  $in: [ "$tags._id", "$$tags_post" ]
                }
              }
            },
            {
              "$replaceWith": "$tags"
            }
          ],
          as: "selectedTags"
        }
      }
    ])
    

    mongoplayground

    方法2先整理数据再查找,方法3先查找再整理数据。虽然 2 和 3 看起来很相似,但我认为方法 3 比方法 2 更快。

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2020-12-18
      • 2021-08-13
      • 2020-03-28
      • 1970-01-01
      相关资源
      最近更新 更多