Creating Database In MongoDB
A Database holds multiple collections of documents in MongoDB and MongoDB holds multiple databases.
MongoDB doesn’t provide any command to create Database, it has a command named use to switch or select the database with the following syntax.
use <databasename>
MongoDB will switch the current database to the provided one if
exist else it will create a database with that name.
Means
for example I am using the use command as
use
TutorialToUs
If the TutorialToUs is already
exist then MongoDB selects the current database as
‘TutorialToUs’if there is no database with that name then it
will createsandswitches to created ‘TutorialToUs;
Note:-
1. MongoDB will create the database only if
that database have minimum a single collection.
Means after usage of use command it will creates db and while leaving from this db(at the time of switching to other db or exit from mongo) if the database doesn’t have a collection then automatically it will be vanished.
Syntax:-
show dbs
This command will return the databasenames and its storage size. Example:-
show dbs
Sample Output:-
local 0.001GB test 0.061GB
Note:-
1. MongoDB will vanish if the DB doesn’t have any collection after using use command. For that see these example
stepno | cmd | output |
---|---|---|
1 | show dbs | local 0.001GB test 0.061GB |
2 | use TutorialToUs | switched to db TutorialToUs |
3 | show dbs | local 0.001GB test 0.061GB |
4 | db.users.insert({name:”Alex”}) | Inserted 1 record(s) in 2ms |
5 | show dbs | local 0.001GB test 0.061GB TutorialToUs 0.000GB |
Note:-
In the above after step2 ‘TutorialToUs’ created only after step4 means after creating a collection for that DB.
Syntax:-
db
it will echo the current database name.