怎么创建MongoDB数据库

MongoDB didn’t provides any command to create “database“. Actually, you don’t need to create it manually, because, MangoDB will create it on the fly, during the first time you save the value into the defined collection (or table in SQL), and database.

For developer from SQL background, we need to create a database, table and insert values into table manually. In MongoDB, you don’t need to mention what you want to create, when first time you save the value into the defined collection (table), under selected database, MangoDB will create the value, collection and database automatically.

Note 
MongoDB contains “ db.createCollection()” to create collection manually, but Not database.

In this guide, we will show you how and when MongoDB will create the database and collections.

1. Show all database

Issue “show dbs” to display all available databases.

MongoDB shell version: 1.8.1
connecting to: test
> show dbs
admin   0.03125GB
local   (empty)

Currently, only two databases are available – “admin” and “local“.

 
2. Define a database name

Issue “use new-databasename” to switch from default database to define database (even non-exists database name will work). However, MangoDB doesn’t create any database yet, until you save something inside.

> use mkyongdb
switched to db mkyongdb
> show dbs
admin   0.03125GB
local   (empty)

P.S Database “mkyongdb” is not created yet.

 
3. Save It

Define a collection named “users“, and save a dummy document(value) inside.

> db.users.save( {username:"mkyong"} )
> db.users.find()
{ "_id" : ObjectId("4dbac7bfea37068bd0987573"), "username" : "mkyong" }
>
> show dbs
admin   0.03125GB
local   (empty)
mkyongdb        0.03125GB

This says, “save this document (value) ‘{username:"mkyong"}‘ into the ‘user’ collection”. When this “save” operation is performed, MangoDB will create the “user” collection, and “mkyongdb” database automatically.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值