Create a Basic User Profile
In this first step, you will create a new database and insert your first user profile document. This will establish the basic structure for storing user information.
First, open the MongoDB interactive shell from your terminal. This is the primary tool for interacting with your MongoDB database.
mongosh
Once inside the shell, you will see a test> prompt. Let's switch to a new database named userprofiles_db. If the database doesn't exist, MongoDB will create it for you when you first store data.
use userprofiles_db
Now, you will insert a document into a collection called profiles. A document in MongoDB is a BSON (binary JSON-like) structure, and a collection is a group of related documents.
Execute the following command to insert a profile for a user named johndoe.
db.profiles.insertOne({
username: "johndoe",
personal_info: {
first_name: "John",
last_name: "Doe",
email: "john.doe@example.com"
},
metadata: {
created_at: new Date(),
account_status: "active"
}
});
This command uses the insertOne() method to add a single document. The document contains a username, a nested personal_info object, and a metadata object to track the creation time and account status.
To confirm that the document was created successfully, you can use the find() method to retrieve it.
db.profiles.find({ username: "johndoe" });
You should see the document you just inserted, along with a unique _id field automatically added by MongoDB. The date and ObjectId will differ in your output.
[
{
_id: ObjectId('656f1a7b2e3a4c5d6e7f8b9a'),
username: 'johndoe',
personal_info: {
first_name: 'John',
last_name: 'Doe',
email: 'john.doe@example.com'
},
metadata: {
created_at: ISODate('2023-12-05T10:30:51.123Z'),
account_status: 'active'
}
}
]