Databases 2 min read

Modeling Many-to-Many Relationships in MongoDB: From SQL to NoSQL

This article explains how to translate a classic SQL many‑to‑many schema for articles and tags into a MongoDB design, showing document structures and practical queries for listing tags, retrieving articles, and filtering by specific tags.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Modeling Many-to-Many Relationships in MongoDB: From SQL to NoSQL

In relational databases a many‑to‑many relationship between articles and tags is usually represented by three tables: Article (Id, Title, …), Tag (Id, Name) and a junction table Relation (ArticleId, TagId). By joining these tables you can query any combination of articles and tags.

MongoDB does not support joins, so the schema must be adapted. A common pattern is to store an array of tag identifiers inside each article document and optionally keep a reverse reference in the tag document.

{
  "id": "505cad",
  "title": "test title",
  "tags": ["tag1", "tag2"]
}

{
  "tag": "tag1",
  "article": ["article1", "article2"],
  "size": 2
}

Example queries:

List all tags: db.article.distinct("tags") → ["tag1", "tag2", "tag3"]

List all articles with their tags: db.article.find({}) returns each document’s _id, title and tags array.

Find articles that contain a specific tag (e.g., "tag2"): db.article.find({tags: {$in: ["tag2"]}}) returns the matching article documents.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SQLDatabase designMongoDBNoSQLmany-to-manyRelationships
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.