CRUD Operations MongoDB Shell

  • CRUD operations in MongoDB are fundamental database tasks that involve Create, Read, Update, and Delete operations. These are typically performed on documents within collections, inside a database. MongoDB’s dynamic schema allows for flexible data storage, and these operations can be executed through the MongoDB shell (mongosh).
  • Below is a complete guide to performing CRUD operations through the MongoDB shell, including how to create a database and collection.
Create a Database in MongoDB
  • MongoDB creates a database only when data is inserted into it. To switch to or create a database:

    use myDatabase

  • If the database does not exist, MongoDB creates it as soon as you add data to a collection.
  • Example: If you switch to `myDatabase`, it will be created as soon as you insert a document.
Create a Collection
  • A collection is similar to a table in SQL databases, and documents are stored in collections. You can create a collection explicitly or implicitly by inserting data.
  • Explicit Collection Creation:

    db.createCollection("myCollection")

  • This will create an empty collection named `myCollection`.
  • Implicit Collection Creation (with document insertion):
    • MongoDB allows you to create a collection automatically when inserting data:

    db.myCollection.insertOne({ name: "John", age: 30 })

  • If `myCollection` does not exist, MongoDB will create it along with the document.
CRUD Operations in MongoDB
  • Create (Insert) Documents
    • MongoDB uses JSON-like documents for data storage. To insert documents into a collection:
  • Insert a single document:

    db.myCollection.insertOne({ name: "Alice", age: 25, profession: "Engineer" })

  • This command inserts one document into the `myCollection` collection.
  • Insert multiple documents:

    db.myCollection.insertMany([
      { name: "Bob", age: 28, profession: "Doctor" },
      { name: "Charlie", age: 35, profession: "Teacher" }
    ])

  • This inserts multiple documents into `myCollection`.
Read (Query) Documents
  • To retrieve or read data, MongoDB provides the `find()` method. You can query documents based on various criteria.
  • Show all documents:

    db.myCollection.find()

  • This will return all the documents in `myCollection`.
  • Find documents with a specific field:

    db.myCollection.find({ name: "Alice" })

  • This returns all documents where the `name` field is "Alice".
  • Query with conditions (e.g., `age` greater than 30):

    db.myCollection.find({ age: { $gt: 30 } })

  • This returns all documents where the `age` field is greater than 30.
  • Pretty print the results:

    db.myCollection.find().pretty()

  • This makes the output more readable by formatting it nicely.
  • Retrieve a single document:

    db.myCollection.findOne({ name: "Alice" })

  • This returns only the first document that matches the query criteria.
Update Documents
  • To update documents, you can use `updateOne()`, `updateMany()`, or `replaceOne()` depending on the number of documents you want to update and the type of update.
  • Update a single document:

    db.myCollection.updateOne(
      { name: "Alice" },  // Query to select the document
      { $set: { age: 26 } }  // Update operation
    )

  • This finds the document where `name` is "Alice" and updates her age to `26`.
  • Update multiple documents:

    db.myCollection.updateMany(
      { age: { $lt: 30 } },  // Query: Select all documents where age is less than 30
      { $set: { status: "Young" } }  // Update operation
    )

  • This updates all documents where `age` is less than 30 by adding a new field `status` with the value "Young".
  • Replace an entire document:

    db.myCollection.replaceOne(
      { name: "Alice" },  // Query: Find the document where name is "Alice"
      { name: "Alice", age: 28, profession: "Manager" }  // New document (replaces the old one)
    )

  • This replaces the entire document where the `name` is "Alice" with a new document.
Delete Documents
  • To remove documents from a collection, MongoDB provides `deleteOne()` and `deleteMany()`.
  • Delete a single document:

    db.myCollection.deleteOne({ name: "Alice" })

  • This deletes one document where the `name` is "Alice".
  • Delete multiple documents:

    db.myCollection.deleteMany({ age: { $lt: 30 } })

  • This deletes all documents where the `age` field is less than 30.
  • Delete all documents:

    db.myCollection.deleteMany({})

  • This deletes all the documents in the collection.
Additional Commands

Check the Current Database
  • To see which database you're currently working in:

    db

  • This command will return the name of the current database.
Show All Databases
  • To view a list of all available databases:

    show dbs


Show Collections in the Current Database
  • To display all the collections in the current database:

    show collections


Delete a Collection
  • To delete a collection, use the `drop()` method:

    db.myCollection.drop()

  • This will delete the `myCollection` from the database.
Delete a Database
  • To delete the current database:

    db.dropDatabase()

  • This deletes the entire database, including all its collections and documents.
  • Example: Complete Workflow
  • Create or switch to a database:

    use employeeDB

  • Create a collection:

    db.createCollection("employees")

  • Insert documents:

    db.employees.insertMany([
      { name: "Alice", age: 30, position: "Engineer" },
      { name: "Bob", age: 35, position: "Manager" }
    ])

  • Read documents:

    db.employees.find().pretty()

  • Update a document:

    db.employees.updateOne({ name: "Alice" }, { $set: { age: 31 } })

  • Delete a document:

    db.employees.deleteOne({ name: "Bob" })

  • Drop a collection:

    db.employees.drop()


Conclusion
  • CRUD operations are essential for interacting with MongoDB databases. These operations are straightforward in MongoDB, thanks to its dynamic schema and flexibility. You can perform these operations via the MongoDB shell (`mongosh`), MongoDB Compass, or programmatically through drivers (e.g., Node.js, Python). By using the commands described above, you can manage and manipulate your MongoDB databases effectively.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...