每日一句
There should be a better way to start a day than waking up every morning.
应该有更好的方式开始新一天, 而不是千篇一律的在每个上午醒来。
数据库操作
查询数据库
查看所有数据库
查看所有数据库,可以使用 show dbs
或者 show databases
命令
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> show databases
查看当前的数据库
查看当前的数据库名:db
命令
> db
test
>
创建或切换数据库
语法
MongoDB 创建数据库的语法格式:use DATABASE_NAME
如果数据库不存在,则创建数据库,否则切换到指定数据库。
实例
以下实例我们创建了数据库 test
> use test1
switched to db test1
> db
test
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
可以看到,我们刚创建的数据库 runoob 并不在数据库的列表中, 要显示它,我们需要向 runoob 数据库插入一些数据。
> db.runoob.insert({"name":"菜鸟就是我"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test1 0.000GB
MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放在 test 数据库中。
删除数据库
语法
MongoDB 删除数据库的语法格式:db.dropDatabase()
实例
以下实例我们删除了数据库 test1。
# 首先,查看所有数据库
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
test1 0.000GB
# 切换到数据库 test1
> use test1
switched to db test1
# 执行删除命令
> db.dropDatabase()
{ "ok" : 1 }
# 查看数据库 test1 是否还存在
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
>
集合操作
集合,类似关系型数据库中的表。
可以显式的创建,也可以隐式的创建。
查看集合
查看当前库中的表/集合:show tables
或者 show collections
命令
> show collections
mycollection
> show tables
mycollection
>
创建集合
显式创建集合
语法格式:db.createCollection(name)
参数说明:
- name - 要创建的集合名称
举例说明:创建一个名为 mycollection 的普通集合。
> db.createCollection("mycollection")
{ "ok" : 1 }
> show tables
mycollection
集合的命名规范参考:集合的命名规范
隐式创建集合
当向一个集合中插入一个文档的是够,如果集合不存在,则会自动创建集合。
具体请看:提示
通常我们使用隐式创建文档即可。
删除集合
语法格式: db.某个集体集合名.drop()
返回值:如果成功删除选定集合,则 drop() 方法返回 true,否则返回 false。
示例:要删除mycollection集合
> show tables
mycollection
> db.mycollection.drop()
true
> show tables
>
文档操作
文档(document)的数据结构和JSON基本一样。
所有存储在集合中的数据都是BSON格式。关于BSON的介绍可以查看:数据模型
查询文档
语法格式:db.collection.find(<query>, [projection])
参数说明:
Parameter | Type | Description |
query | document | 可选。使用查询运算符指定选择筛选器。若要返回集合中的所有文档,请省略此参数或传递空文档( {} )。 |
projection | document | 可选。指定要在与查询筛选器匹配的文档中返回的字段(投影)。若要返回匹配文档中的所有字段,请省略此参数 |
实例1:查询所有 db.comment.find()
或 db.comment.find({})
> db.comment.find()
{ "_id" : ObjectId("61bfc69ab5617497c0621b00"), ... }
{ "_id" : "1", "articleid" : "100001", ... }
{ "_id" : "2", "articleid" : "100001", ... }
{ "_id" : "3", "articleid" : "100001", ... }
{ "_id" : "4", "articleid" : "100001", ... }
{ "_id" : "5", "articleid" : "100001", ... }
> db.comment.find({})
{ "_id" : ObjectId("61bfc69ab5617497c0621b00"), ... }
{ "_id" : "1", "articleid" : "100001", ... }
{ "_id" : "2", "articleid" : "100001", ... }
{ "_id" : "3", "articleid" : "100001", ... }
{ "_id" : "4", "articleid" : "100001", ... }
{ "_id" : "5", "articleid" : "100001", ... }
# 按一定条件来查询 只需要在find()中添加参数即可
> db.comment.find({userid:'1003'})
{ "_id" : "4", "articleid" : "100001", "userid" : "1003", ... }
{ "_id" : "5", "articleid" : "100001", "userid" : "1003", ... }
>
提示:每条文档会有一个叫_id的字段,这个相当于我们原来关系数据库中表的主键,当你在插入文档记录时没有指定该字段,MongoDB会自动创建,其类型是ObjectID类型。
实例2:投影查询(Projection Query)