One-to-One Relationship example

  • Let's use MongoDB Shell to create a one-to-one relationship with both embedding and referencing approaches.
Example 1: Embedding Approach
  • Step 1: Insert Data (Embedding)
  • In this approach, we embed the Profile document directly inside the User document.
  • Create the Users collection with an embedded Profile field:


    use myDatabase   # Switch to or create the database

    db.users.insertOne({
      _id: 1,
      name: "John Doe",
      email: "john@example.com",
      profile: {
        age: 30,
        gender: "Male",
        address: "123 Main Street"
      }
    })

  • Here, the profile field is embedded directly into the users document. 
  • Step 2: Query Data (Embedding)
  • To retrieve a user with their embedded profile, simply query the users collection:


    db.users.findOne({ _id: 1 })

    // Output:
    {
      "_id": 1,
      "name": "John Doe",
      "email": "john@example.com",
      "profile": {
        "age": 30,
        "gender": "Male",
        "address": "123 Main Street"
      }
    }

Example 2: Referencing Approach

  • Step 1: Insert Data (Referencing)
  • In this approach, we store the Profile in a separate collection and use a reference (e.g., profile_id) in the Users collection.
  • Create the Profiles collection and insert the profile data:


  db.profiles.insertOne({
    _id: 101,
    age: 30,
    gender: "Male",
    address: "123 Main Street"
  })

  • Create the Users collection with a reference to the profile:


  db.users.insertOne({
    _id: 1,
    name: "John Doe",
    email: "john@example.com",
    profile_id: 101  # Reference to the profile
  })

  • Step 2: Query Data (Referencing)
  • To get a user and their profile, you need to perform two queries or use MongoDB’s $lookup (aggregation framework) to join the two collections.
Option 1: Simple Query with Two Separate Lookups
  • 1. Query the user to get their profile_id:


    var user = db.users.findOne({ _id: 1 })

  • 2. Query the profiles collection to get the related profile using the profile_id:


    db.profiles.findOne({ _id: user.profile_id })

Option 2: Using Aggregation with $lookup to Join the Data

  • You can use the $lookup stage to join users and profiles collections in a single query:


  db.users.aggregate([
    {
      $lookup: {
        from: "profiles",            // Collection to join
        localField: "profile_id",    // Field from the users collection
        foreignField: "_id",         // Field from the profiles collection
        as: "profile"                // Output array field
      }
    }
  ])

  // Output:
  [
    {
      "_id": 1,
      "name": "John Doe",
      "email": "john@example.com",
      "profile_id": 101,
      "profile": [
        {
          "_id": 101,
          "age": 30,
          "gender": "Male",
          "address": "123 Main Street"
        }
      ]
    }
  ]

Explanation:

  • Embedding is simple and effective when the data is tightly related and will be fetched together. In this case, everything related to a user is stored in one document.
  • Referencing helps keep collections normalized and is useful when the related data (e.g., profiles) might change often or when it’s large and you don’t always need to fetch the entire profile with every user query.
Conclusion:
  • For one-to-one relationships, you can choose between embedding and referencing based on how you want to manage your data.
  • Embedding is good for simpler, tightly coupled data, while referencing offers more flexibility and normalization.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...