tags:

views:

74

answers:

1

Assuming a setup like this:

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'));

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'.

+5  A: 

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"]
}

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.

Niels van der Rest
@Niels van der Rest: +1 for the great insight. Will there be a performance difference if I use multiple collections over a single collection especially when I plan on indexing two columns inside my collection?
Legend
@Legend: Thanks! By using multiple collections, you won't have to index the `type` field, which will save you some RAM. But in terms of query performance the differences will be negligible if you have defined the right indexes.
Niels van der Rest