Create a Database and Insert a Document
In MongoDB, you don't need to explicitly create a database. It is created automatically when you first store data in it. To switch to a new database, use the use command.
Let's switch to a database named mylab_database. In the mongosh shell, type:
use mylab_database
The shell will respond with switched to db mylab_database. Even though the database is not yet created, you are now working in its context.
Data in MongoDB is stored in collections, which are groups of documents. A document is a set of key-value pairs. Let's create a users collection by inserting our first document.
Use the insertOne() method to add a single document to the users collection:
db.users.insertOne({ name: "JohnDoe", age: 30, city: "NewYork" })
Let's break down this command:
db: Represents the current database (mylab_database).
users: The name of the collection. It will be created automatically.
insertOne(): The method to insert one document.
{...}: The document itself, containing fields like name, age, and city.
MongoDB will confirm the insertion and return the unique _id it generated for the document:
{
acknowledged: true,
insertedId: ObjectId("...")
}
The ObjectId is a unique identifier automatically assigned to every document.
Now, let's verify that the document was added. Use the find() method to view all documents in the users collection:
db.users.find()
The output will display the document you just inserted:
[
{
_id: ObjectId("..."),
name: 'JohnDoe',
age: 30,
city: 'NewYork'
}
]