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" }]
});