8.5. Inserting documents into MongoDB: Creating a database in MongoDB
Page 13 | Listen in audio
MongoDB is an open source NoSQL database that provides support for different forms of data. It is used in many modern web development applications for its ease of use, flexibility, and scalability. In this section, we will discuss how to create a database in MongoDB and how to insert documents into it.
Creating a database in MongoDB
To start using MongoDB, we first need to create a database. In MongoDB, the 'use' command is used to create a new database. If the database mentioned in the command already exists, it will be opened for transactions. If it doesn't exist, it will be created. The syntax is as follows:
use database_name
For example, to create a database called 'myDataBase', you would use the following command:
use myDatabase
You will see a message saying 'switched to db myBancoDeDados', indicating that the database has been created and is ready to use.
Inserting documents into MongoDB
After creating a database, you can start inserting documents into it. In MongoDB, data is stored in documents, which are similar to records or rows in relational databases. Each document is a collection of fields and values, similar to a JSON object.
To insert a document into a collection, we use the 'insert' command. The syntax is as follows:
db.collection_name.insert(document)
For example, to insert a document into the 'users' collection of our 'myBancoDeDados' database, we would use the following command:
db.usuarios.insert({name: "João", age: 25, email: "[email protected]"})
This will create a new document in the 'users' collection with the fields 'name', 'age' and 'email' and their respective values. If the 'users' collection does not exist, it will be created.
You can insert multiple documents at once using the 'insertMany' command. The syntax is as follows:
db.collection_name.insertMany([document1, document2, ...])
For example, to insert multiple documents into the 'users' collection, we would use the following command:
db.usuarios.insertMany([{name: "João", age: 25, email: "[email protected]"}, {name: "Maria", age: 30, email: "[email protected]"} ])
This will create two new documents in the 'users' collection.
Conclusion
Creating a database in MongoDB and inserting documents into it are simple and straightforward tasks. However, they form the basis for working with MongoDB. Understanding these basic operations is essential to working effectively with this powerful NoSQL database.
In the next section, we will discuss how to query documents in MongoDB, which will allow you to retrieve data efficiently and effectively.
Now answer the exercise about the content:
What is the procedure for creating a database and inserting documents into MongoDB?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: