Can you achieve primary key – foreign key relationships in MongoDB?

We can achieve primary key-foreign key relationship by embedding one document inside another. For example: An address document can be embedded inside customer document.

MongoDB, as a NoSQL database, does not natively support primary key-foreign key relationships in the same way as traditional relational databases like MySQL or PostgreSQL. MongoDB uses a flexible schema design called BSON (Binary JSON) and collections to store documents, and it does not enforce a strict schema with predefined relationships.

However, you can achieve similar functionalities by embedding documents or referencing documents within other documents. There are two common approaches:

  1. Embedding Documents: You can embed related data directly within a document. For example, if you have a collection of users and a collection of comments, you might embed the comments directly within each user document.
    {
    "_id": 1,
    "username": "john_doe",
    "email": "john@example.com",
    "comments": [
    {"text": "Great post!", "date": "2024-01-24"},
    {"text": "Interesting topic!", "date": "2024-01-25"}
    ]
    }

    This way, the comments are embedded within the user document.

  2. Referencing Documents: Alternatively, you can reference documents by including the _id field of one document within another. For example, you might have a collection of users and a separate collection of comments, where each comment document references the _id of the user who made the comment.User document:
    {
    "_id": 1,
    "username": "john_doe",
    "email": "john@example.com"
    }

    Comment document:

    {
    "_id": 101,
    "user_id": 1,
    "text": "Great post!",
    "date": "2024-01-24"
    }

    In this case, you manually maintain the relationship between the user and their comments.

While MongoDB doesn’t enforce referential integrity like traditional relational databases, it provides flexibility in designing data models that suit your application’s needs. It’s essential to carefully design your schema based on your specific use case and query patterns.