Create Database and Collection - MongoDB


In MongoDB, you can create and drop databases using the use and db.dropDatabase() commands. Here's how you can do it in the MongoDB shell:

Create a Database:

To create a new database or switch to an existing database, you can use the use command. If the specified database doesn't exist, MongoDB will create it when you insert data into it.

use youtube

Replace youtube with the name of the database you want to create or use. After running this command, you are now working with the youtube database.

Drop a Database:

To drop a database and permanently remove all its data, you can use the db.dropDatabase() method while connected to the specific database you want to drop. Make sure to be cautious when using this command, as it cannot be undone.

db.dropDatabase()

After running this command, the current database (the one you're connected to) will be deleted. Make sure you are connected to the correct database before executing this command.

Remember to exercise caution when dropping databases, as this action will result in the loss of all data within the specified database. Always ensure you have backups or data recovery procedures in place as needed.

Show all Databases

To show a list of all the databases in MongoDB, you can use the show dbs command in the MongoDB shell. This command will display a list of all the databases on the MongoDB server, along with their sizes.

Here's how you can use the show dbs command:

  • Open your MongoDB shell by running the mongo command in your terminal or command prompt.
  • Once you're in the MongoDB shell, run the following command:
show dbs

OR

show databases

After running this command, MongoDB will display a list of all the databases on the server, along with their sizes in megabytes (MB).

Please note that MongoDB only shows databases that have data in them. If a database is empty (i.e., it doesn't contain any collections or documents), it may not appear in the list generated by the show dbs command.

Create Collection in MongoDB

In MongoDB, you don't need to explicitly create a collection before inserting data into it. Collections are created automatically when you insert a document into them. So, if you run the following command:

db.products.insertOne({"name":"Pen"})

MongoDB will create a collection named "products" if it doesn't already exist, and it will insert the specified document into that collection

After running the insertOne command, you can start querying and working with the "products" collection as it has been created and populated with the document provided.

db.products.find()

The db.createCollection() method is used to explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules. If you are not specifying these options, you do not need to explicitly create the collection since MongoDB creates new collections when you first store data for the collections

db.createCollection("products");

OR

db.createCollection( <name>,
  {
    capped: <boolean>,
    timeseries: {                  // Added in MongoDB 5.0
        timeField: <string>,        // required for time series collections
        metaField: <string>,
        granularity: <string>,
        bucketMaxSpanSeconds: <number>,  // Added in MongoDB 6.3
        bucketRoundingSeconds: <number>  // Added in MongoDB 6.3
    },
    expireAfterSeconds: <number>,
    clusteredIndex: <document>,  // Added in MongoDB 5.3
    changeStreamPreAndPostImages: <document>,  // Added in MongoDB 6.0
    size: <number>,
    max: <number>,
    storageEngine: <document>,
    validator: <document>,
    validationLevel: <string>,
    validationAction: <string>,
    indexOptionDefaults: <document>,
    viewOn: <string>,
    pipeline: <pipeline>,
    collation: <document>,
    writeConcern: <document>
  }
)
    

Show All Collections:

To list all collections in the current database, you can use the show collections command in the MongoDB shell:

show collections

OR

show tables

Rename a Collection:

In MongoDB, you can use the renameCollection() method to rename a collection. The syntax for renaming a collection is as follows:

db.oldCollectionName.renameCollection("newCollectionName")

In your case, you want to rename the "products" collection to "items". You can do it like this:

db.products.renameCollection("items")

This command will rename the "products" collection to "items" in the same database. Please note that you should have the necessary permissions to perform this operation, and it's a good practice to ensure that your application code is updated to reflect the new collection name if needed.

Remember that renaming a collection or database should be done with caution, especially in a production environment. Ensure that you have proper backups and that you understand the potential impact on your application before making these changes.

Drop a Collection:

To drop (delete) a collection in MongoDB, you can use the db.collectionName.drop() method. Replace collectionName with the name of the collection you want to drop. Be cautious when using this command, as it permanently deletes the collection and all its documents.

For example, to drop the "products" collection, you would run:

db.products.drop()