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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
