Last Updated:

MongoDB : Create Database and Collection

MongoDB
 

This tutorial focuses on creating a database in MongoDB and creating a Collection.
In this lesson, you will create a database and create a collection that plays the role of tables in relational databases.

This article will provide an example of working with MongoDB using the cmd command-line interpreter.
But on the official website there is a convenient program (Compass) for working with Mongo databases and collections.


  1. Let's assume that mongoDB is already running. Open the cmd command prompt interpreter and run the command to launch mongo.exe.
    To do this, you must specify the path to mongo.exe in cmd.
    In my case it is: "C:\Program Files\MongoDB\Server\4.2\bin\mongo.exe"
  2. Create a new database using the command: use with the name of the database.
    use my_database

    my_database is the name of the database
    .
    After running the command, you should see the following message.

     
  3. Let's create a collection.
    To create a collection, you need to run the following command in cmd:

    db.createCollection("posts")

    posts - the name of the collection. You can specify your


    After running the command, you should see the following message.
  4. Let's delete the collection.
    To delete a collection, you must run the command with the name of the collection after db and method drop:

    If the collection is successfully deleted, an informational message will be displayed - "true".
    db.posts.drop()