Circle
Circle

Reputation: 187

Tag-based search model in Mongodb

I am creating a tag based search engine for various kind of things in mongodb.
I have blogs document, testimonials document, comments documents, books document and images document and all these have array of tags field.

Now when I fetch a book, which have certain tags associated with it, I would like to also fetch blogs and testimonials and comments with those tags. I would like to the same when I fetch a blog .. fetch rest with tags that blog have. I am designing my database model. what is the best way to handle these kind of tag based search.
currently what I am thinking is

is this the best way ? how should I design model?

Update : I will perform search more frequently.

Upvotes: 9

Views: 7374

Answers (1)

Ivan Beldad
Ivan Beldad

Reputation: 2371

If you need to repeat tags in multiple collections, I would rather do a tags collection itself.

Why would I move tags into their own collection?

Think if you need to change the name of one tag in the future, maybe because of a mistake like a typo, you'll need to iterate over all your collections searching for this tag to fix it. Wouldn't it be easier if you only need to replace in one place?

Embed arrays and objects in one document is a powerful tool, but there are times when it's not the best solution. This case is one of them, and you should prevent as much as you can repetition.

Official documentation talking about avoid repetition.

Collection Structure

Create a tags collection and add their ObjectId to the tags array in the other documents instead of the tag itself. Like below.

// tags collection
{
  _id: <ObjectId1>
  title: "trending"
}


// all other documents (blogs, testimonials...)
{
  _id: <ObjectId2>
  tags: [
    <ObjectId1>
  ],
  // other stuff...
}

Fetching tag related documents in one hit

When you fetch one document you can get all its tags and look for other documents with related tags using the operator $in, like this:

db.blogs.find({
  tags: {
    $in: [
      <ObjectId1>,
      <ObjectIdX>,
      // other tags ids
    ]
  } 
})

And this will return at once all the documents matching one or more tags.

More about $in operator.

Other tips

Well used indexes have a great impact on performance. This isn't the place to teach about how they works, but mongodb have multikey indexex and in your concrete case is obviuos which one, tags.

Example:

db.blogs.createIndex( { "tags": 1 } )

Upvotes: 13

Related Questions