Blockchain Collection Examples for MongoDB Clusters

Hey folks,

In recent work there’s a consistent problem I see for those who work in Blockchain and choosing to use MongoDB for the collections.

This is just a couple examples of what will seriously make your lives and your jobs a lot easier when you put your DB collections together:

Blocks Collection:
The blocks collection will store information about each block in the blockchain. Each document in this collection represents a block and should contain these fields:

  • _id: A unique identifier for the block.
  • index: The index or height of the block in the blockchain.
  • timestamp: The timestamp when the block was mined.
  • previousHash: The hash of the previous block.
  • hash: The hash of the current block.
  • nonce: A value used in the proof-of-work algorithm (if applicable).
  • transactions: An array of references to transactions in the transactions collection.
{
  "_id": ObjectId("2222333444222111888"),
  "index": 0,
  "timestamp": ISODate("2023-21-09T10:00:00Z"),
  "previousHash": "00000000000000000000000000000000",
  "hash": "aaaaaaaaaaaaaqqq...",
  "nonce": 12345,
  "transactions": [
    ObjectId("1111111111111111111111"),
    ObjectId("2222222222222222222222"),
    ObjectId("2222333333444444555555")
  ]
}

Transactions Collection:
The transactions collection will store individual transactions on the blockchain. Each document in this collection represents a transaction and contains these fields (or it should, but this is where a lot of places I’ve seen the last couple months royally mess up):

  • _id: A unique identifier for the transaction.
  • sender: The sender’s address.
  • recipient: The recipient’s address.
  • amount: The transaction amount.
  • timestamp: The timestamp when the transaction was created.

It doesn’t need a whole lot of bloat, just straight to the point. The “amount” and maybe a couple fields for what specifically is being sold or bought, or traded what for what, but generally this is a basic template.

{
  "_id": ObjectId("11111111111111111"),
  "sender": "Zachary",
  "recipient": "David",
  "amount": 200.00,
  "timestamp": ISODate("2023-21-09T10:05:00Z")
}

To optimize queries and ensure efficient access to blockchain data, consider creating indexes on fields commonly used for filtering and sorting, such as index, timestamp, sender, and recipient.

Additionally, you can implement features like pagination, transaction history retrieval, and blockchain analytics by designing appropriate queries based on your application’s needs. This is just a basic outline of stuff, and there’s a lot more you can do the more complex your needs are, but fundamentals first.

Hope this helps for anyone who finds this trying to look up blockchain with MongoDB.