MongoDB FAQ: How do I create a MongoDB database?
To create a MongoDB database, follow these steps:
- “Use” the database.
- Create a collection in the database.
- Verify that you got what you wanted.
Short example
For example, to “use” a database named pizzas
, start your mongo
client and then issue this command:
use pizzas
Next, create a collection in this database. For instance, create a document in a customers
collection like this:
db.customers.save({"firstName":"Alvin", "lastName":"Alexander"})
Next, verify that your document was created with this command:
db.customers.find()
You should see output from MongoDB showing that your document was created.
Complete example
Here’s what this looks like when I try it with my own MongoDB installation, including my commands and the output from MongoDB:
> use pizzas switched to db pizzas > db pizzas > db.customers.save({"firstName":"Alvin", "lastName":"Alexander"}) > db.customers.find() { "_id" : ObjectId("520e3cebf2b2417375cbc438"), "firstName" : "Alvin", "lastName" : "Alexander" } > db pizzas
Notice that I used the db
command twice, and it showed I am in the pizzas
database. After issuing these commands I can also issue the MongoDB show dbs
command, and it shows my new pizzas
database:
> show dbs finance 0.203125GB local (empty) pizzas 0.203125GB <== the new 'pizzas' database test 0.203125GB
If you needed to create a new MongoDB database, I hope these examples have been helpful.