【问题标题】:Mongo DB aggregate match not returning valueMongodb聚合匹配不返回值
【发布时间】:2021-07-28 22:10:48
【问题描述】:

我有以下 mongo db 模式,我正在尝试构建一个聚合查询,该查询在 repo 键下的 github_open_issues 下搜索,并且可以返回一个匹配所有以 repoA 为值的值。我尝试了以下作为我的查询,但它没有返回任何结果。我有点困惑为什么这不起作用,因为我有另一个具有类似于此模式的数据库,并且这种类型的查询在那里工作,但这里的东西似乎有所不同并且不起作用。我还整理了这个互动示例mongoplayground

查询

db.collection.aggregate([
  {
    "$unwind": "$github_open_issues"
  },
  {
    "$match": {
      "github_open_issues.repo": {
        "$in": [
          "repoA"
        ]
      }
    }
  },
  
])

架构

[
  {
    "github_open_issues": {
      "0": {
        "git_url": "https://github.com/",
        "git_assignees": "None",
        "git_open_date": "2019-09-26",
        "git_id": 253113,
        "repo": "repoA",
        "git_user": "userA",
        "state": "open"
      },
      "1": {
        "git_url": "https://github.com/",
        "git_assignees": "None",
        "git_open_date": "2019-11-15",
        "git_id": 294398,
        "repo": "repoB",
        "git_user": "userB",
        "state": "open"
      },
      "2": {
        "git_url": "https://github.com/",
        "git_assignees": "None",
        "git_open_date": "2021-04-12",
        "git_id": 661208,
        "repo": "repoA",
        "state": "open"
      }
    },
    "unique_label_seen": {
      "568": {
        "label_name": "some label",
        "times_seen": 12,
        "535": {
          "label_name": "another label",
          "times_seen": 1
        }
      }
    }
  }
]

【问题讨论】:

  • github_open_issues 字段是对象,它实际上是数据库中的对象吗?
  • 首先感谢您的问题,但我不完全理解它,但是 github_open_issues 是对象,它实际上在数据库中。我有完整的工作示例,我在这里复制了我的问题mongoplayground.net/p/IdPWMU1yPdX

标签: mongodb mongodb-query aggregation-framework pymongo


【解决方案1】:
  • $objectToArraygithub_open_issues 对象转换为键值格式的数组
  • $filter 迭代上述转换数组的循环并过滤您的搜索条件
  • $match 过滤 github_open_issues 不为空
  • $arrayToObjectgithub_open_issues 数组转换为对象
db.collection.aggregate([
  {
    $addFields: {
      github_open_issues: {
        $filter: {
          input: { $objectToArray: "$github_open_issues" },
          cond: { $in: ["$$this.v.repo", ["repoA"]] }
        }
      }
    }
  },
  { $match: { github_open_issues: { $ne: [] } } },
  { $addFields: { github_open_issues: { $arrayToObject: "$github_open_issues" } } }
])

Playground

【讨论】:

  • 谢谢,这绝对是我想做的,但是如果没有addFields,还有其他方法可以做到这一点吗?我们正在运行的 mongo 版本是 3.2.10,看起来直到 3.9 才支持它我也看到将我们的版本升级为旧版本。
  • 使用 $set 而不是 $addFields,但是其他操作符 $objectToArray 和 $arrayToObject 不会工作,因为它是从 mongodb 3.4.4 开始的。所以在 mongodb 3.2 中没有其他方法可以做到这一点。
【解决方案2】:

您的查询是正确的,但是您在 github_open_issues.repo 中放置错误的架构中的数据您的对象按 {"0": {values...}, "1" 之类的数字放置:{values... }} 无法获得您想要的值。您现在可以查看游乐场playground

【讨论】:

  • 这不起作用,因为架构中存在数字值并且无法删除它们。
  • 那么另一个答案是给你的。
猜你喜欢
  • 2014-10-14
  • 2018-06-13
  • 2016-05-20
  • 1970-01-01
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 2020-06-24
相关资源
最近更新 更多