MongoDB is an open-source, NoSQL JSON-like document database that is created using C++ language. Creating a MongoDB Database is pretty straight forward. This guide is all about how to create MongoDB Database with the CLI ie mongosh.
Prerequisite
- MongoDB installation
In this previous guide, we already installed MongoDB.
Connect to the MongoDB shell with the credentials that you’d already set using the following command:
# mongosh --port 27017 --authenticationDatabase "admin" -u "mongoadmin" -p Enter password: ********** Current Mongosh Log ID: 64d51e3846bf0d89d2b526bc Connecting to: mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&authSource=admin&appName=mongosh+1.10.3 Using MongoDB: 6.0.8 Using Mongosh: 1.10.3 For mongosh info see: https://docs.mongodb.com/mongodb-shell/
Show MongoDB Databases
Using the command below, we are able to list the already existing databases.
test> show dbs admin 132.00 KiB config 72.00 KiB local 72.00 KiB
Please note that admin and local are default databases for every MongoDB instance.
Create MongoDB database
There is no ‘create’ command in the mongosh. For you to create a database, you will first need to switch the context to a non-existing database using the use command:
use DATABASE_NAME
Example:
test> use technnix_db switched to db technnix_db technnix_db> show dbs admin 132.00 KiB config 96.00 KiB local 72.00 KiB technnix_db>
The use keyword is used to switch to the mentioned database in case it exists or it creates a new one if its non-existent.
MongoDB only creates the database when you first store data in that database. This data could be a collection or a document. This is the reason why we are unable to see the newly created database from the command above.
Collection
: Â equivalent of an RDBMS Relational Database Management System table. Its a collection/groupings of MongoDB Documents.
Document
: The basic unit of data in MongoDB.
Insert Data to Database
db.collection.insert()
command is used to add a document to the database
technnix_db> db.user.insert({name: "Ezekiel Mogaka", age: 35, website: "technnix.com"}) DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite. { acknowledged: true, insertedIds: { '0': ObjectId("64d529c046bf0d89d2b526bd") } }
Verification
Lets verify whether the database was created and data inserted onto it.
technnix_db> show dbs admin 132.00 KiB config 108.00 KiB local 72.00 KiB technnix_db 40.00 KiB technnix_db> db.user.find() [ { _id: ObjectId("64d529c046bf0d89d2b526bd"), name: 'Ezekiel Mogaka', age: 35, website: 'technnix.com' } ]
Conclusion
That it for now. For more information, please refer to the official MongoDB documentation.