Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

MongoDB: Collections and Documents

Introduction

MongoDB is a NoSQL database that stores data in a flexible, JSON-like format. The fundamental unit of data in MongoDB is the document, which is stored in a collection. Understanding collections and documents is key to effectively working with MongoDB.

What are Collections?

A collection in MongoDB is analogous to a table in relational databases. It is a grouping of MongoDB documents.

Key Features of Collections:

  • Collections can hold many documents.
  • Documents in a collection can have different structures.
  • Collections are created automatically when you insert a document.

What are Documents?

A document is a basic unit of data in MongoDB and is stored in BSON (Binary JSON) format. Each document is a set of key-value pairs.

Document Structure:

{
    "_id": "ObjectId(\"507f191e810c19729de860ea\")",
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com"
}

CRUD Operations

Create

db.collectionName.insertOne({
    "name": "Jane Doe",
    "age": 25,
    "email": "jane.doe@example.com"
});

Read

db.collectionName.find({ "name": "Jane Doe" });

Update

db.collectionName.updateOne(
    { "name": "Jane Doe" },
    { $set: { "age": 26 } }
);

Delete

db.collectionName.deleteOne({ "name": "Jane Doe" });

Best Practices

  • Use meaningful names for collections.
  • Keep documents small and efficient.
  • Utilize indexes to improve query performance.
  • Use schema validation for data integrity.

FAQ

What is the maximum size of a document in MongoDB?

The maximum size of a single document in MongoDB is 16 MB.

Can I have multiple collections in a database?

Yes, a MongoDB database can contain multiple collections.