In the mongo shell, using `use DATABASE_NAME` command, We can create a MongoDB.
`use ` command will do the below actions.
2) will switch to the database If the database exists
use DATABASE_NAME
If you want to create a new database with your favorite name,
> use learnmongodb
switched to db learnmongodb
>
Verify DB:
In the following command, We can get the selected database.
> db
learnmongodb
>
Database List:
If you want to get the list of created databases, use below command.
> show dbs
DBNAME 0.000GB
admin 0.000GB
local 0.000GB
test 0.000GB>
Just now We have created a new database `learnmongodb`. But It is not available in the DB list because of no records in DB.
If you don't have any document in the database, It will not be displayed in the DB list.
We will get the database in the list Once we start to insert the documents or insert collection.
We can add a document in `topics` collection like this.
> db.topics.insert({"name":"Create MongoDB"})
WriteResult({ "nInserted" : 1 })
>
Now using `find()`, You can verify that collection was created with the document.
> db.topics.find()
{ "_id" : ObjectId("5b7fb8f43bbf689b29dc0d67"), "name" : "Create MongoDB" }
>
Again run `show dbs` command to get your database in the list.
> show dbs
DBNAME 0.000GB
admin 0.000GB
learnmongodb 0.000GB
local 0.000GB
test 0.000GB
>
Complete shell command:
> use learnmongodb
switched to db learnmongodb
> db
learnmongodb
> show dbs
DBNAME 0.000GB
admin 0.000GB
local 0.000GB
test 0.000GB
> db.topics.insert({"name":"Create MongoDB"})
WriteResult({ "nInserted" : 1 })
> db.topics.find()
{ "_id" : ObjectId("5b7fb8f43bbf689b29dc0d67"), "name" : "Create MongoDB" }
> show dbs
DBNAME 0.000GB
admin 0.000GB
learnmongodb 0.000GB
local 0.000GB
test 0.000GB
>
Note:
- `test` is the default MongoDB. If you add any document without selecting a database, It will be stored in the default `test` database.
0 Comments