Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

How should I model many-to-many tag relationships in MongoDB?

clock icon

asked 1 month ago

message icon

2

eye icon

399

Questions have many tags and tags have many questions. I can see two options:

  1. Embed an array of tag ids on the question document.
  2. Keep a separate join collection.

Is there a reason to prefer one when I need "questions for a tag" and "tags for a question" to both be fast?

2 Answers

Do both, and accept the duplication.

The embedded array makes rendering a question cheap — one document, no join. The join collection makes "all questions for tag X" cheap and gives you somewhere to hang a compound unique index:

1TagQuestionSchema.index({ tag: 1, question: 1 }, { unique: true })
1TagQuestionSchema.index({ tag: 1, question: 1 }, { unique: true })

The cost is that writes must update both, so wrap them in a transaction. For a read-heavy site that trade is almost always worth it.

One caveat on the embedded array: keep a denormalised questions counter on the tag itself. Otherwise the tags page has to run a countDocuments per tag, which gets slow fast.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions