Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Understanding Collections

Understanding collections in MongoDB

Collections in MongoDB are analogous to tables in relational databases. A collection is a group of MongoDB documents. Unlike tables in a relational database, collections do not have a predefined schema, allowing documents within a collection to have different fields and structures.

Creating a Collection

Collections are created implicitly when the first document is inserted. However, you can also create a collection explicitly using the createCollection command.

Create Collection Command

db.createCollection("myCollection")

Key Features of Collections

Some key features of collections in MongoDB include:

  • Dynamic Schema: Collections do not enforce document structure, allowing flexibility in data modeling.
  • Indexing: Collections support indexing to improve query performance.
  • Sharding: Collections can be sharded across multiple servers for horizontal scalability.

Example: Creating and Querying a Collection

Below is an example of creating a collection and inserting documents into it:

Commands

// Creating a collection
db.createCollection("employees")

// Inserting documents
db.employees.insertMany([
    { name: "Alice", age: 28, position: "Manager" },
    { name: "Bob", age: 24, position: "Engineer" },
    { name: "Charlie", age: 35, position: "CEO" }
])

// Querying the collection
db.employees.find({ position: "Engineer" })