Creation, Display, and Deletion of DataBases, Collections, and Documents

  • Here's a detailed explanation of how to perform various operations in MongoDB, covering the creation, display, and deletion of databases, collections, and documents, as well as checking the current database and displaying its contents.
  • MongoDB operations are performed using the MongoDB shell (via the `mongo` command-line interface), but these commands can also be executed using MongoDB Compass or from a programming language using a driver.
Show Databases
  • To view all databases in MongoDB:

    show dbs

  • This command lists all the databases available in your MongoDB instance.
  • Example Output:

    admin    0.000GB
    config   0.000GB
    local    0.000GB
    mydb     0.000GB


Create a Database
  • MongoDB does not explicitly use the `CREATE DATABASE` command. Instead, a database is created implicitly when you insert data into it.
  • To create a new database, you must first switch to it (even if it doesn’t exist yet):

    use myNewDatabase

  • If `myNewDatabase` does not exist, MongoDB will create it as soon as data (such as a collection) is inserted into it.
Delete a Database
  • To delete an existing database, use the `dropDatabase()` command. First, switch to the database you want to delete:

    use myNewDatabase

  • Then, delete the database:

    db.dropDatabase()

  • This command deletes the current database, including all its collections and documents.
Create a Collection
  • A collection in MongoDB is a group of documents, similar to a table in relational databases. Collections are created either explicitly or implicitly when you insert data.
  • Explicit Collection Creation:

    db.createCollection("myCollection")

  • This creates an empty collection named `myCollection` in the current database.
Implicit Collection Creation:
  • You can also create a collection automatically by inserting a document into a non-existent collection:

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

  • This command creates the collection `myCollection` if it doesn’t already exist and inserts a document into it.
Insert Documents
  • Documents in MongoDB are equivalent to rows in a relational database table. They are stored in collections.
  • Insert a Single Document:

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

  • This inserts one document into the `myCollection` collection.
  • Insert Multiple Documents:

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

  • This inserts multiple documents into the `myCollection` collection at once.
Check the Current Database
  • To check which database you are currently working in:

    db

  • This command returns the name of the current database.
  • Example Output:
    • myNewDatabase
Show Collections
  • To display all collections within the current database:

    show collections

  • This command lists all the collections in the current database.
Show Documents
  • To display all the documents in a collection, use the `find()` method.
  • Show All Documents in a Collection:

    db.myCollection.find()

  • This command retrieves and displays all the documents in the `myCollection` collection.
  • Example Output:

    {
        "_id": ObjectId("601f1e17c5efba45608f70d1"),
        "name": "Alice",
        "age": 25,
        "profession": "Engineer"
    }
    {
        "_id": ObjectId("601f1e17c5efba45608f70d2"),
        "name": "Bob",
        "age": 40,
        "profession": "Teacher"
    }
    {
        "_id": ObjectId("601f1e17c5efba45608f70d3"),
        "name": "Charlie",
        "age": 35,
        "profession": "Doctor"
    }

  • Show Documents with Specific Fields:
  • You can also query documents with specific criteria. For example, to show documents where the `age` is greater than `30`:

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

  • This query retrieves all documents where the `age` field is greater than 30.
  • Show Documents in a Pretty Format:
    • To make the document output easier to read, use the `pretty()` method:

    db.myCollection.find().pretty()

  • This will display each document in a more readable format.
Delete a Collection
  • To delete a collection, use the `drop()` method:

    db.myCollection.drop()

  • This command deletes the `myCollection` collection from the current database.
Delete Documents
  • To delete specific documents from a collection:
  • Delete a Single Document:

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

  • This deletes one document that matches the criteria (in this case, where the `name` is "Alice").
  • Delete Multiple Documents:

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

  • This deletes all documents where the `age` is less than 30.
Example Workflow
  • Here’s a basic workflow to create a database, add collections, insert documents, and display data:
  • Create or Switch to a Database:
    
    use myNewDatabase

  • Create a Collection:

    db.createCollection("users")

  • Insert Documents:

    db.users.insertMany([
      { name: "John", age: 28, profession: "Engineer" },
      { name: "Jane", age: 34, profession: "Designer" }
    ])

  • Show Collections:

    show collections

  • Display All Documents:

    db.users.find().pretty()

  • Delete a Document:

    db.users.deleteOne({ name: "John" })

  • Delete the Collection:

    db.users.drop()

  • Drop the Database:

    db.dropDatabase()


Conclusion
  • By using the above MongoDB commands, you can easily manage databases, collections, and documents. These operations form the core of working with MongoDB, whether you’re performing CRUD operations, managing schema, or querying data. MongoDB's dynamic schema allows you to work more flexibly with your data compared to traditional relational databases.

No comments:

Post a Comment

Date and Time related aggregation functions ($year, $month, $dayOfMonth, $hour, $minute, $second, $dayOfWeek, $dateToString, $dateSubtract, $dateAdd, $isoWeek, $isoDayOfWeek, $dateTrunc, $dateFromString, $dateToParts, $dateFromParts, $dateDiff, $week)

In this blog post, we will explore Date/Time-related Aggregation Functions in MongoDB. MongoDB provides a robust set of aggregation operator...