假设这样的设置:
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'的所有内容。
无法一次查询多个集合。
如果文档都是相同的常规类型,最好的方法是将所有文档存储在同一个集合中。在您的示例中,博客帖子和新闻项都是一种“内容”。
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的无模式特性;虽然两种文档类型可能具有不同的属性,但它们都可以存储在同一个集合中。这允许您查询所有内容,或仅查询某些类型的内容,具体取决于您的要求。
无法一次查询多个集合。
如果文档都是相同的常规类型,最好的方法是将所有文档存储在同一个集合中。在您的示例中,博客帖子和新闻项都是一种“内容”。
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的无模式特性;虽然两种文档类型可能具有不同的属性,但它们都可以存储在同一个集合中。这允许您查询所有内容,或仅查询某些类型的内容,具体取决于您的要求。
从Mongodb 3.2开始,现在可以在聚合管道中使用$ lookup阶段,允许您“连接”另一个集合。
执行左外连接到同一个非unsharded集合
数据库从“已加入”集合中过滤文档
处理。 $ lookup阶段在字段之间进行相等匹配
来自输入文档的文档字段
“加入”系列。
资源