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