Skip to main content

Single Collection Pattern

The single collection pattern groups related documents of different types into a single collection

use case:

  • many to many relationships
  • one to many relationship
    • catalog of product items
    • shopping carts

variant1:

  • books, users, reviews
  • docType field and relatedTo array
  • many to many

To apply the first variant of the Single Collection pattern to the books catalog, we added the docType and relatedTo fields to each document for the Books, Users and Reviews collections and moved the documents to the Books Catalog collection. For example:

{
   "review_id": 378,
  "docType": "review",
   "relatedTo": [202356]
   ...
}

Next, we created an index on the relatedTo array to support queries for related documents:

db.books_catalog.createIndex({ relatedTo: 1 })

variant2:

  • overloaded field
  • one to many

To apply the second variant of the Single Collection pattern to the books catalog in our bookstore app, we added an overloaded sc_id field to our documents. Book documents used the book id in the sc_id field. For review documents the sc_id field contains the book id and the review id separated by a slash. This way we overloaded the field in order to support queries for related documents. Finally we moved the documents to the Books Catalog collection.

Book document example:

{
   "book_id": 202356,
   "sc_id": "202356"
   ...
}

Review document example:

{
   "review_id": 378,
   "sc_id": "202356/378"
   ...
}

Next, we created an index on the sc_id field to support queries for related documents:

db.books_catalog.createIndex({ sc_id: 1 })