MongoDB doesn’t have a CREATE DATABASE
statement like SQL does.
In MongoDB, you create a database simply by switching to a non-existent database, then inserting data.
Example
Here’s an example of creating a new database:
use PetHotel
Result:
switched to db PetHotel
That creates a new database called PetHotel
and makes it the current database.
However, the database is only partially created. It isn’t fully created until you insert data.
If we run the show dbs
command to see what databases we have, it won’t be shown.
show dbs
Result:
admin 0.000GB config 0.000GB local 0.000GB
This is the default set of databases that were installed with MongoDB. If you have other databases, you’ll see them here too.
But the point is, our newly created PetHotel
database is nowhere to be seen!
Insert Data
To fully create the database, we need to insert some data. Even just a small amount is enough.
Example:
db.pets.insert({ name: "Fetch" })
Result:
WriteResult({ "nInserted" : 1 })
This message tells us that one document was inserted.
Now when we run show dbs
again, we can see our newly created database.
show dbs
Result:
PetHotel 0.000GB admin 0.000GB config 0.000GB local 0.000GB
Collections
A database contains collections. In our case, we’ve already created a collection called pets
.
When you insert data, you use the syntax like this:
db.<collection>.insert()
Where <collection>
is the name of the collection to insert data into. If the collection doesn’t exist, it will be created.
In our case, we used the following command:
db.pets.insert({ name: "Fetch" })
Which created a collection called pets
(because it didn’t already exist).
Check the Data
You can use the find()
collection method to check the data in the collection.
Example:
db.pets.find()
Result:
{ "_id" : ObjectId("5fe02d3937b49e0faf1af20b"), "name" : "Fetch" }
As expected, our document is returned.
You’ll notice that it also has an extra field. It has an _id
field, which we didn’t specify when we added the document.
The _id
field is a special field. It’s used as an identifier for the document. If the document does not specify an _id
field, then MongoDB will add the _id
field and assign a unique ObjectId
for the document before inserting.
Alternatively, you can provide your own _id
field and assign it your own value. However, note that the _id
value must be unique within the collection to avoid duplicate key error.