代码之家  ›  专栏  ›  技术社区  ›  Tim Fountain

MongoDB:交叉收集查询

  •  11
  • Tim Fountain  · 技术社区  · 15 年前

    假设设置如下:

    blogposts
    {
      title:"Example",
      slug:"example-post"
      tags: ["foo", "bar"]
    },
    {
      title:"Example2",
      slug:"example2"
      tags: ["foo"]
    }
    
    news
    {
      headline: "Test"
      slug: "test-news"
      tags: ["bar"]
    }
    

    我知道我可以得到所有带有特定标签的博客文章:

    $cursor = $blogposts->find(array('tags' => 'bar'));
    

    但是,是否有任何方法可以一次查询多个集合以获取带有标记的所有文档?例如,用标签“bar”显示所有内容。

    2 回复  |  直到 8 年前
        1
  •  13
  •   Niels van der Rest    15 年前

    无法同时查询多个集合。

    最好的方法是将所有文档存储在同一集合中,如果这些文档都是相同的常规类型。在您的示例中,博客文章和新闻项目都是一种“内容”。

    content
    {
      type: "blogpost",
      title: "Example",
      slug: "example-post"
      tags: ["foo", "bar"]
    },
    {
      type: "blogpost",
      title: "Example2",
      slug: "example2"
      tags: ["foo"]
    },
    {
      type: "news",
      headline: "Test"
      slug: "test-news"
      tags: ["bar"]
    }
    

    这种方法利用了MongoDB的无模式特性;尽管两种文档类型可能具有不同的属性,但它们都可以存储在同一个集合中。这允许您根据需要查询所有内容,或者只查询某些类型的内容。

        2
  •  0
  •   Darxtar    8 年前

    由于MongoDB3.2,现在可以在聚合管道中使用$lookup阶段,允许您针对另一个集合“加入”。

    对同一个未加密的集合执行左外部联接 从__joined_集合中筛选文档的数据库 处理。$lookup阶段在字段之间进行相等匹配 来自输入文档,其中包含来自 _156;加入_157;收藏。

    Source