【问题标题】:Using an array as a query argument in MongoDB在 MongoDB 中使用数组作为查询参数
【发布时间】:2022-02-04 04:41:14
【问题描述】:

我有一个如下结构的 MongoDB 数据库:

人员数据库, 个人文件 1:

{
      _id: ObjectId("61f9d7dd837c1fb343a21550"),
      alias: [
        "Lewis",
        "Colt"
      ]
}

报告数据库, 报告文件 1:

{
      _id: ObjectId("61fc1f59bf1edbf56d24acad"),
      people: [
        "Lewis",
        "Jake"
      ],
      Report: "They talked about Python and C."
    }

报告数据库, 报告文件 2:

{
      _id: ObjectId("61fc29e73cd13b44ffc4074b"),
      people: [
        "Colt",
        "Justin"
      ],
      Report: "They tweaked the cogs."
    }

是否可以在个人文档中使用别名的数组来拉出底部的两个文档? 例如,我可以在搜索报告时插入 Lewis 作为查询,它会找到 Person Document,查看 alias 中提供的不同名称,然后在 people 数组中找到包含 alias 数组中任何字符串的 Report Documents 并显示相关报道。

与 Lewis 一起获取报告, 认识到刘易斯也是柯尔特, 在 People 数组中显示带有 Lewis 或 Colt 的报告。

更多上下文,我使用 Python 3.10 和 Pymongo 和 Discord.py,使用机器人来显示文档。

这在 MongoDB 中可行吗?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您可以在$lookup 中创建子管道。计算people 集合中的alias 数组和report 集合中的people 数组之间的集合交集。 $match那些$setIntersection的大小> 0。

    db.people.aggregate([
      {
        "$match": {
          // put your query here
          alias: "Lewis"
        }
      },
      {
        "$lookup": {
          "from": "report",
          "let": {
            alias: "$alias"
          },
          "pipeline": [
            {
              $match: {
                $expr: {
                  $gt: [
                    {
                      $size: {
                        "$setIntersection": [
                          "$$alias",
                          "$people"
                        ]
                      }
                    },
                    0
                  ]
                }
              }
            }
          ],
          "as": "matchedReports"
        }
      },
      {
        "$unwind": "$matchedReports"
      },
      {
        "$replaceRoot": {
          "newRoot": "$matchedReports"
        }
      }
    ])
    

    这是Mongo playground 供您参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 2013-04-11
      • 2019-03-02
      • 2017-05-12
      • 2022-10-16
      • 2020-06-15
      • 2011-12-17
      • 1970-01-01
      相关资源
      最近更新 更多