MongoDB之初级命令语句
一.MongoDB概念解析
1.术语对比
2.数据类型
二.MongoDB创建数据库
语法
MongoDB 创建数据库的语法格式如下:
use DATABASE_NAME
如果数据库不存在,则创建数据库,否则切换到指定数据库。
实例
创造数据库agatha:
use agatha
switched to db agatha
db
agatha
如果你想查看所有数据库,可以使用 show dbs 命令:
show dbs
admin 0.000GB
agatha 0.000GB
config 0.000GB
local 0.000GB
可以看到,我们刚创建的数据库 agatha 并不在数据库的列表中, 要显示它,我们需要向 agatha 数据库插入一些数据。
db.agatha.insert({"name":"agatha"})
再次查看所有数据库:
show dbs
admin 0.000GB
agatha 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放在 test 数据库中。
注意: 在 MongoDB 中,集合只有在内容插入后才会创建! 就是说,创建集合(数据表)后要再插入一个文档(记录),集合才会真正创建
三.MongoDB删除数据库
语法
MongoDB 删除数据库的语法格式如下:
db.dropDatabase()
实例
以下实例我们删除了数据库 agatha。
show dbs
admin 0.000GB
agatha 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
接下来我们切换到数据库 agatha:
use agatha
switched to db agatha
执行删除命令:
db.dropDatabase({"dropped":"agatha","ok":1})
最后,我们再通过 show dbs 命令数据库是否删除成功:
show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
四.MongoDB创建集合
语法
db.createCollection(name, options)
实例
运用默认数据库test
use test
switched to db test
创建集合
db.createCollection("library")
db.createCollection("library1")
查看test数据库中的集合
show collections
library
library1
在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合。
五.MongoDB删除集合
语法
db.collection.drop()
实例
查看有哪些集合
show collections
library
library1
删除 library1 集合
db.library1.drop()
true
再次查看集合
show collections
library
可以看出集合 library1 已经被删除
六.MongoDB插入文档
语法
db.COLLECTION_NAME.insert(document)
实例
插入数据
db.library.insert({"BID":"b1","name":"agatha","book":"math","likes":10000})
db.library.insert({"BID":"b2","name":"fang","book":"python","likes":76460})
db.library.insert({"BID":"b3","name":"fyx","book":"english","likes":12342})
db.library.insert({"BID":"b4","name":"fyx","book":"chinese","likes":5630})
db.library.insert({"BID":"b5","name":"agatha","book":"linux","likes":76530})
db.library.insert({"BID":"b6","name":"fang","book":"java","likes":53346})
db.library.insert({"BID":"b7","name":"agatha","book":"history","likes":3452})
db.library.insert({"BID":"b8","name":"fyx","book":"hbase","likes":45733})
db.library.insert({"BID":"b9","name":"fang","book":"hadoop","likes":567655})
db.library.insert({"BID":"b10","name":"agatha","book":"phoenix","likes":4563457})
db.library.insert({"BID":"b11","name":"fyx","book":"mongo","likes":437325})
db.library.insert({"BID":"b12","name":"agatha","book":"mysql","likes":7500})
七.MongoDB查询文档
语法
db.collection.find(query, projection)
实例
查询 library 集合中文档信息
db.library.find()
八.MongoDB更新文档
语法
db.collection.update(<query>,<update>)
实例
查看集合中文档信息
db.library.find()
这里将 b12 改为 b112 然后更新
db.library.update({"BID":"b12"},{$set:{"BID":"b112"}})
再次查看集合中文档信息
db.library.find()
可见已经更改
九.MongoDB删除文档
语法
db.collection.remove(<query>,<justOne>)
实例
查看集合中文档信息
db.library.find()
这里删除 b112
db.library.remove({"BID":"b112"})
再次查看集合中文档信息
db.library.find()
可见 b112 已经删除