Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: cross-collection queries

Tags:

php

mongodb

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

like image 591
Tim Fountain Avatar asked Sep 19 '10 11:09

Tim Fountain


People also ask

Does MongoDB support query join between collections?

Does MongoDB supports query joins between collections ? No MongoDB doesnot supports query joins between collections.

How do I link two collections in MongoDB?

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.

Can a MongoDB have multiple collections?

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.


1 Answers

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.

like image 178
Niels van der Rest Avatar answered Oct 11 '22 13:10

Niels van der Rest