When working with MongoDB, one of the first steps is creating collections and inserting documents. This process is essential to establish the database structure and allow data manipulation. In this chapter, we will cover how to create collections in MongoDB and insert documents into them.
Creating Collections in MongoDB
In MongoDB, a collection is a group of documents. It is equivalent to a table in relational databases. Each document in a collection has a different number of fields, size, and content. The collection does not enforce a rigid schema, meaning documents do not need to have the same structure or fields.
To create a collection, we use the 'db.createCollection()' command. Suppose we want to create a collection called 'students'. The command would be:
db.createCollection("students")
This command creates a new collection called 'students'. If the collection is created successfully, MongoDB returns an object confirming the operation.
Inserting Documents into MongoDB
After creating a collection, the next step is to insert documents into it. In MongoDB, a document is a set of key-value pairs. It is similar to a JSON object.
To insert a document into a collection, we use the 'db.collection.insert()' command. Suppose we want to insert a document into the 'students' collection. The document has two fields: 'name' and 'age'. The command would be:
db.students.insert({name: "John", age: 22})
This command inserts a document into the 'students' collection. The document has two fields: 'name' and 'age'. If the document is inserted successfully, MongoDB returns an object confirming the operation.
Creating and Inserting Documents in an Operation
In MongoDB, we can also create a collection and insert a document into it in a single operation. To do this, we use the 'db.collection.insert()' command. Suppose we want to create a collection called 'teachers' and insert a document into it. The document has two fields: 'name' and 'subject'. The command would be:
db.teachers.insert({name: "Jane", subject: "Mathematics"})
This command creates a new collection called 'teachers' and inserts a document into it. The document has two fields: 'name' and 'subject'. If the collection is created and the document is inserted successfully, MongoDB returns an object confirming the operation.
Conclusion
In summary, creating collections and inserting documents are fundamental operations in MongoDB. They establish the structure of the database and allow data manipulation. When creating a collection, we use the 'db.createCollection()' command. To insert a document into a collection, we use the 'db.collection.insert()' command. We can also create a collection and insert a document into it in a single operation.
Understanding these operations is essential for working with MongoDB. They form the basis for more complex operations, such as updating and deleting documents, querying data, and more. Therefore, it is advisable to practice them and become comfortable with them.