This tutorial is meant to provide a comprehensive understanding of MongoDB's fundamental units of storage: documents and collections. By the end of this tutorial, you will understand how to structure your data effectively within MongoDB.
You will learn:
- What documents and collections are in MongoDB
- How to create, read, update, and delete documents and collections
- Best practices for structuring and manipulating your MongoDB data
Prerequisites:
- Basic understanding of MongoDB
- Basic knowledge of JavaScript
- MongoDB and Node.js installed on your local machine
Documents: In MongoDB, a document is a basic unit of data, analogous to a row in a relational database. Documents are composed of field-and-value pairs and have a dynamic schema. This means that documents in the same collection don't need to have the same set of fields, and the data type for a field can vary across documents within a collection.
Collections: A collection is a group of MongoDB Documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema.
To create a document, you would use the insertOne()
or insertMany()
methods. Here is an example:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
const doc = { item: "card", qty: 15 };
collection.insertOne(doc, function(err, res) {
console.log("Document inserted");
client.close();
});
});
In the above code, we have created a new document with two fields, item
and qty
, and inserted it into the devices
collection.
Collections are created using the createCollection()
method.
client.connect(err => {
const db = client.db("mydb");
db.createCollection("products", function(err, res) {
console.log("Collection created!");
client.close();
});
});
To read from a collection, you can use the find()
method:
client.connect(err => {
const collection = client.db("test").collection("devices");
collection.find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
client.close();
});
});
In this code, we are retrieving all documents from the devices
collection.
In this tutorial, we have learned about MongoDB's fundamental units of storage: documents and collections. We've seen how to create, read, update, and delete both documents and collections.
Next steps for learning could include diving deeper into MongoDB's querying capabilities, learning how to build indexes, and understanding MongoDB's aggregation framework.
Some additional resources include the official MongoDB documentation, MongoDB University, and various MongoDB tutorials on websites like Codecademy, Udacity, and freeCodeCamp.
Exercise 1: Create a new collection in your database called users
and insert a new document into it with fields name
and email
.
Exercise 2: Insert multiple documents at once into the users
collection.
Exercise 3: Retrieve all documents from the users
collection where the user's name starts with 'A'.
Exercise 4: Update a document in the users
collection.
Exercise 5: Delete a document from the users
collection.
Exercise 6: Drop the users
collection.
For each exercise, try to accomplish the task on your own, then check your solution with the respective MongoDB documentation section. Don't forget to test your code frequently to make sure everything works as expected. Happy coding!