MongoDB Create Collection

MongoDB Create Collection

MongoDB Create Collection

MongoDB automatically creates a collection when you insert the first document. However, you can manually create collections with specific options like validation rules or storage engine settings. This guide explains how to create a collection using MongoDB Shell, Node.js (Mongoose), and Compass.

1. Create a Collection Automatically

MongoDB creates a collection automatically when you insert a document if the collection does not exist.

Example: Insert a Document to Create a Collection

use myDatabase db.myCollection.insertOne({ name: "John Doe", age: 30, city: "New York" })
  • If myCollection does not exist in myDatabase, MongoDB creates it automatically.
  • The document { name: "John Doe", age: 30, city: "New York" } is inserted.

2. Create a Collection Explicitly

You can explicitly create a collection using the createCollection() method.

Syntax:

db.createCollection("collectionName", options)

Example: Create a Simple Collection

use myDatabase db.createCollection("users")
  • Creates a collection named users in myDatabase.

3. Create a Collection with Options

You can specify options like capped collection, size limit, and max documents.

Example: Create a Capped Collection (Fixed Size)

db.createCollection("logs", { capped: true, size: 100000, max: 500 })
  • capped: true → Limits the collection’s size.
  • size: 100000 → Maximum storage in bytes.
  • max: 500 → Maximum number of documents.

Example: Create a Collection with a Validation Schema

db.createCollection("employees", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "age"], properties: { name: { bsonType: "string", description: "Must be a string" }, age: { bsonType: "int", description: "Must be an integer" } } } } })
  • Ensures that every document in employees has name (string) and age (integer).

4. List All Collections

To check the collections in a database:

show collections

or

db.getCollectionNames()

5. Drop (Delete) a Collection

To remove a collection from the database:

db.myCollection.drop()
  • Deletes myCollection from the current database.

Summary

MethodDescription
db.createCollection("name")Creates an empty collection
db.createCollection("name", options)Creates a collection with options
show collectionsLists all collections in the database
db.collectionName.drop()Deletes a collection

Would you like help with specific use cases? 🚀

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close