MongoDB:交叉收集查询 [英] MongoDB: cross-collection queries

查看:58
本文介绍了MongoDB:交叉收集查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设这样的设置:

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

news
{
  headline: "Test"
  slug: "test-news"
  tags: ["bar"]
}

我知道我可以使用特定标签获取所有博客文章:

I know I can get all the blog posts with a specific tag:

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

但是有没有办法一次查询多个集合以获取带有标签的所有文档?例如.显示所有带有标签"bar"的内容.

but is there any way to query multiple collections at once in order to get all documents with the tag? E.g. to show all content with the tag 'bar'.

推荐答案

无法一次查询多个集合.

There's no way to query multiple collections at once.

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

The best approach would be to store all documents in the same collection, if the documents are all of the same general type. In your example, both blog posts and news items are a type of 'content'.

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的无模式本质;尽管两种文档类型可能具有不同的属性,但是它们都可以存储在同一集合中.这使您可以查询所有内容,或仅查询某些类型的内容,具体取决于您的要求.

This approach takes advantage of the schema-less nature of MongoDB; although both document types may have different properties, they can all be stored in the same collection. This allows you to query all of your content, or only some type(s) of content, depending on you requirements.

这篇关于MongoDB:交叉收集查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆