Build MongoDB User Profiles

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, we will learn how to build a comprehensive MongoDB user profile schema. We will design profile fields to store various user information, including personal details, contact information, user settings, preferences, and metadata for tracking profile updates. By the end of this lab, you will have a flexible and efficient user profile document structure that can be used to manage user data in your MongoDB-powered applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/DataTypesGroup(["`Data Types`"]) mongodb(("`MongoDB`")) -.-> mongodb/SchemaDesignGroup(["`Schema Design`"]) mongodb(("`MongoDB`")) -.-> mongodb/ArrayandEmbeddedDocumentsGroup(["`Array and Embedded Documents`"]) mongodb(("`MongoDB`")) -.-> mongodb/RelationshipsGroup(["`Relationships`"]) mongodb/BasicOperationsGroup -.-> mongodb/update_document("`Update Document`") mongodb/DataTypesGroup -.-> mongodb/manage_array_elements("`Manage Array Elements`") mongodb/SchemaDesignGroup -.-> mongodb/design_order_schema("`Design Order Schema`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/create_embedded_documents("`Create Embedded Documents`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/query_embedded_documents("`Query Embedded Documents`") mongodb/RelationshipsGroup -.-> mongodb/create_document_references("`Create Document References`") subgraph Lab Skills mongodb/update_document -.-> lab-422077{{"`Build MongoDB User Profiles`"}} mongodb/manage_array_elements -.-> lab-422077{{"`Build MongoDB User Profiles`"}} mongodb/design_order_schema -.-> lab-422077{{"`Build MongoDB User Profiles`"}} mongodb/create_embedded_documents -.-> lab-422077{{"`Build MongoDB User Profiles`"}} mongodb/query_embedded_documents -.-> lab-422077{{"`Build MongoDB User Profiles`"}} mongodb/create_document_references -.-> lab-422077{{"`Build MongoDB User Profiles`"}} end

Design Profile Fields

In this step, we'll design a flexible MongoDB user profile schema that can store various user information efficiently. We'll explore how to create a comprehensive user profile document with different types of fields.

Understanding User Profile Schema

Before we start coding, let's open the MongoDB shell and begin designing our user profile structure. First, launch the MongoDB shell:

mongosh

Now, let's create a database specifically for our user profiles:

use userprofiles_db

We'll design a user profile schema with multiple field types:

db.profiles.insertOne({
  username: "johndoe",
  personal_info: {
    first_name: "John",
    last_name: "Doe",
    email: "[email protected]",
    age: 30
  },
  contact_details: {
    phone: "+1-555-1234",
    address: {
      street: "123 Main St",
      city: "San Francisco",
      country: "USA"
    }
  },
  preferences: {
    language: "English",
    theme: "dark",
    notifications: {
      email: true,
      sms: false
    }
  },
  metadata: {
    created_at: new Date(),
    last_updated: new Date(),
    account_status: "active"
  }
});

Schema Design Explanation

Let's break down our user profile schema:

  1. username: A unique identifier for the user
  2. personal_info: Stores basic personal details
  3. contact_details: Contains contact information with nested address
  4. preferences: Captures user settings and preferences
  5. metadata: Tracks account-related information

To verify our document, we'll retrieve it:

db.profiles.find({ username: "johndoe" });

Add Contact Information

In this step, we'll expand our user profile by adding more detailed contact information to our MongoDB document. We'll demonstrate how to update existing documents and add nested contact details.

Updating User Profile with Contact Information

Let's continue working in our MongoDB shell from the previous step. We'll update the existing "johndoe" profile with more comprehensive contact information:

db.profiles.updateOne(
  { username: "johndoe" },
  {
    $set: {
      contact_details: {
        phone: {
          mobile: "+1-555-1234",
          work: "+1-555-5678"
        },
        email: {
          personal: "[email protected]",
          work: "[email protected]"
        },
        social_media: {
          linkedin: "linkedin.com/in/johndoe",
          twitter: "@johndoe"
        },
        emergency_contact: {
          name: "Jane Doe",
          relationship: "Spouse",
          phone: "+1-555-9876"
        }
      }
    }
  }
);

Understanding the Update Operation

Let's break down the update operation:

  • updateOne() modifies a single document matching the filter
  • $set replaces or adds the specified fields
  • We've added nested phone, email, social media, and emergency contact details

To verify our update, let's retrieve the updated profile:

db.profiles.find({ username: "johndoe" });

Adding Multiple Contact Methods

Now, let's add another user profile to demonstrate multiple contact information approaches:

db.profiles.insertOne({
  username: "janesmirth",
  personal_info: {
    first_name: "Jane",
    last_name: "Smirth",
    age: 28
  },
  contact_details: {
    primary_contact: {
      email: "[email protected]",
      phone: "+1-555-4321"
    },
    communication_preferences: {
      preferred_contact_method: "email",
      contact_times: ["evening", "weekend"]
    }
  }
});

This example shows an alternative way to structure contact information with different nested fields.

Include User Settings

In this step, we'll expand our user profiles by adding comprehensive user settings that demonstrate the flexibility of MongoDB's document model. We'll create and update user settings with various configuration options.

Designing User Settings Schema

Let's continue in our MongoDB shell and update the existing profiles with detailed user settings:

db.profiles.updateOne(
  { username: "johndoe" },
  {
    $set: {
      user_settings: {
        privacy: {
          profile_visibility: "friends",
          data_sharing: {
            analytics: true,
            marketing: false
          }
        },
        accessibility: {
          theme: "dark",
          font_size: "medium",
          high_contrast: false
        },
        notifications: {
          email_notifications: {
            marketing: false,
            system_updates: true,
            weekly_digest: true
          },
          push_notifications: {
            enabled: true,
            channels: ["messages", "updates"]
          }
        },
        security: {
          two_factor_authentication: {
            enabled: true,
            method: "app"
          },
          login_history: {
            max_sessions: 3,
            alert_new_device: true
          }
        }
      }
    }
  }
);

Understanding User Settings Structure

Our user settings include:

  • Privacy controls
  • Accessibility preferences
  • Notification settings
  • Security configurations

Let's add another profile with a different settings approach:

db.profiles.insertOne({
  username: "alexwong",
  personal_info: {
    first_name: "Alex",
    last_name: "Wong",
    age: 35
  },
  user_settings: {
    preferences: {
      language: "English",
      timezone: "America/New_York",
      currency: "USD"
    },
    communication: {
      preferred_contact: "email",
      communication_frequency: "weekly"
    },
    display_options: {
      color_scheme: "light",
      compact_view: true
    }
  }
});

To verify our updates, let's retrieve the profiles:

db.profiles.find({
  $or: [{ username: "johndoe" }, { username: "alexwong" }]
});

Store User Preferences

In this step, we'll explore how to store and manage user preferences using MongoDB's flexible document model. We'll demonstrate different approaches to capturing and organizing user-specific preferences.

Creating Detailed User Preferences

Let's continue in our MongoDB shell and expand our user profiles with more granular preference tracking:

db.profiles.updateOne(
  { username: "johndoe" },
  {
    $set: {
      preferences: {
        content_preferences: {
          interests: ["technology", "photography", "travel"],
          content_categories: {
            news: ["tech", "science"],
            entertainment: ["movies", "podcasts"]
          }
        },
        learning_preferences: {
          learning_style: "visual",
          preferred_topics: ["data science", "machine learning"],
          skill_levels: {
            programming: "intermediate",
            design: "beginner"
          }
        },
        consumption_preferences: {
          media_consumption: {
            reading_time: "evening",
            podcast_speed: 1.5,
            video_quality: "HD"
          },
          shopping_preferences: {
            category_interests: ["electronics", "books"],
            budget_range: {
              min: 50,
              max: 500
            }
          }
        }
      }
    }
  }
);

Understanding Preference Structure

Our preference schema includes:

  • Content preferences
  • Learning interests
  • Consumption habits

Let's add another profile with a different preference approach:

db.profiles.insertOne({
  username: "emilychan",
  personal_info: {
    first_name: "Emily",
    last_name: "Chan",
    age: 28
  },
  preferences: {
    lifestyle_preferences: {
      fitness_goals: ["weight loss", "muscle gain"],
      diet_type: "vegetarian",
      workout_frequency: "3-4 times/week"
    },
    professional_preferences: {
      career_interests: ["data analysis", "product management"],
      skill_development: {
        current_focus: "Python programming",
        target_proficiency: "advanced"
      }
    },
    entertainment_preferences: {
      music_genres: ["indie", "electronic"],
      movie_genres: ["sci-fi", "documentary"],
      podcast_categories: ["technology", "self-improvement"]
    }
  }
});

To verify our updates, let's retrieve the profiles:

db.profiles.find({
  $or: [{ username: "johndoe" }, { username: "emilychan" }]
});

Track Profile Updates

In this step, we'll implement a robust mechanism for tracking profile updates in MongoDB. We'll demonstrate how to maintain an audit trail of changes and manage profile modification history.

Creating an Update Tracking Mechanism

Let's update our existing profiles to include a comprehensive update tracking system:

// Update John Doe's profile with update tracking
db.profiles.updateOne(
  { username: "johndoe" },
  {
    $set: {
      update_history: {
        created_at: new Date("2024-01-15T10:30:00Z"),
        last_updated: new Date(),
        version: 1,
        update_log: [
          {
            timestamp: new Date(),
            updated_fields: ["contact_details", "user_settings", "preferences"],
            update_type: "profile_enhancement",
            updated_by: "self"
          }
        ]
      },
      metadata: {
        profile_completeness: 85,
        last_login: new Date(),
        account_status: "active"
      }
    },
    $push: {
      "update_history.update_log": {
        timestamp: new Date(),
        updated_fields: ["preferences"],
        update_type: "preference_update",
        updated_by: "system"
      }
    }
  }
);

Understanding Update Tracking

Our update tracking includes:

  • Creation timestamp
  • Last update timestamp
  • Version tracking
  • Detailed update log
  • Metadata about profile status

Let's add another profile with a different update tracking approach:

db.profiles.insertOne({
  username: "sarahlee",
  personal_info: {
    first_name: "Sarah",
    last_name: "Lee",
    age: 32
  },
  update_tracking: {
    profile_versions: [
      {
        version: 1,
        created_at: new Date(),
        update_summary: "Initial profile creation"
      }
    ],
    recent_changes: {
      total_updates: 0,
      last_significant_update: null
    },
    verification_status: {
      email_verified: false,
      phone_verified: false
    }
  }
});

To demonstrate update tracking, let's perform an update and log the changes:

db.profiles.updateOne(
  { username: "sarahlee" },
  {
    $push: {
      "update_tracking.profile_versions": {
        version: 2,
        created_at: new Date(),
        update_summary: "Added contact information"
      }
    },
    $set: {
      "update_tracking.recent_changes.total_updates": 1,
      "update_tracking.recent_changes.last_significant_update": new Date()
    }
  }
);

Verify the updated profiles:

db.profiles.find({
  $or: [{ username: "johndoe" }, { username: "sarahlee" }]
});

Summary

In this lab, you learned how to design a flexible MongoDB user profile schema that can store various user information efficiently. You explored creating a comprehensive user profile document with different types of fields, including personal information, contact details, user preferences, and metadata. You also learned how to update existing user profiles by adding more detailed contact information, including nested address data. Throughout the lab, you practiced using the MongoDB shell to create, query, and update user profile documents.

Other MongoDB Tutorials you may like