MongoDB / MongoDB Basics

Understanding Documents and Collections

This tutorial will delve into MongoDB's fundamental units of storage: documents and collections. You'll learn how to structure your data effectively within MongoDB.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of MongoDB, including collections, documents, and CRUD operations.

Understanding Documents and Collections in MongoDB

1. Introduction

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

2. Step-by-Step Guide

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.

Creating Documents

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.

Creating Collections

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();
  });
});

3. Code Examples

Reading from a Collection

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.

4. Summary

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.

5. Practice Exercises

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help