【问题标题】:MongoDB: Select from one collection based on another collectionMongoDB:基于另一个集合从一个集合中选择
【发布时间】:2022-01-19 01:02:01
【问题描述】:

我是 MongoDB 新手,我正在尝试找到一个满足所需参数的类别。我有两个集合,categories(类别列表)和 ref_categories(管理嵌套的类别关系)

collection categories:
[
  {
      "id": "A1001",
      "key": "3dmodels",
  },
  {
      "id": "A1002",
      "key": "animals",
  },
  {
      "id": "A1003",
      "key": "birds",
  },
  {
      "id": "A1004",
      "key": "reptiles",
  },
  {
      "id": "A1005",
      "key": "birds",
  }
]

collection categories_ref:
[
  {
      "category_id": "A1001", // 3dmodels parented to
      "p_category_id": "root", // root
  },
  {
      "category_id": "A1002", // animals parented to
      "p_category_id": "A1001", // 3dmodels
  },
  {
      "category_id": "A1003", // birds parented to
      "p_category_id": "A1002", // animals
  },
  {
      "category_id": "A1004", // reptiles parented to
      "p_category_id": "A1002", // animals
  },
  {
      "category_id": "A1005", // birds parented to
      "p_category_id": "A1004", // reptiles
  }
]

您会注意到,在我的类别集合中,有两个“鸟类”条目,但是它们每个都有不同的父类别。

我正在尝试创建一个查询,允许我通过键和父类别键查找类别。

伪示例....我想查找“鸟类”,但该条目的父项名为“动物”。否则返回null。

预期的输出是

// find category_key: "birds" parent_category_key: "animals"

{
   "id": "A1003",
   "key": "birds",
}

【问题讨论】:

  • 我不完全理解这个问题,因为似乎有多个问题,但如果你想找到最后一次登记的动物餐,该日期也必须存储在数据库中。到目前为止,我们看到的所有数据都是 ID 和 Key。
  • @Edward 抱歉,我复制并粘贴了,我修复了帖子。

标签: json mongodb


【解决方案1】:

您可以将$lookup 与匹配两个条件的管道一起使用:

  1. 基于id 加入。类别id 与参考category_id 相同。
  2. 还要检查p_category_id 是所需的代码。

然后您可以$match 不获取连接结果为空的元素(即保留存在值的元素)。

db.categories.aggregate([
  {
    "$match": {"key": "birds"}
  },
  {
    "$lookup": {
      "from": "categories_ref",
      "let": {"id": "$id"},
      "pipeline": [
        {
          "$match": {
            "$expr": {
              "$and": [
                {
                  "$eq": ["$category_id","$$id"]
                },
                {
                  "$eq": ["$p_category_id","A1002"]
                }
              ]
            }
          }
        }
      ],
      "as": "cat_ref"
    }
  },
  {
    "$match": {"cat_ref": {"$ne": []}}
  },
  {
    "$project": {"cat_ref": 0}
  }
])

例如here

【讨论】:

  • 您的解决方案会有所帮助,但请记住,我尝试使用“鸟类”和“动物”的密钥而不是您展示的父 ID。
  • 但是,您的收藏中哪里有“动物”价值?我使用了A1002,因为它是“动物”的关键(仅在 cmets 中)。
  • 动物属于 db 类别。我想我应该得到所有以动物为键的类别,并循环遍历它们并检查哪个有“鸟”的孩子并将其作为最终结果返回。这最终才是最有效的方法。
猜你喜欢
  • 1970-01-01
  • 2015-09-14
  • 2015-07-21
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 2022-01-26
相关资源
最近更新 更多