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'.
Does MongoDB supports query joins between collections ? No MongoDB doesnot supports query joins between collections.
For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents.
As mentioned above, a single database can have multiple collections. The following creates multiple collections. Use the show collections commands to list all the collections in a database. To delete a collection, use the db.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With