MongoDB 是什么
MongoDB 是一种非关系型数据库(NoSQL)。
MongoDB中的术语解释
文档(document):形如
{ name: "sue", <---- field: value age: 26, <---- field: value status: "A" <---- field: value groups: [ "news", "sports" ] <---- field: value }
的一条记录,就叫文档。文档由 field and value pairs
组成,与JSON对象相似。
区分大小写
field唯一 , 不可重复
文档可嵌套
键值对是有序的
集合:集合就是一组文档
SQL 与 MongoDB 术语比较
database | database | 数据库 |
table | collection | 表、集合 |
row | document | 记录、文档 |
column | field | 字段、域 |
index | index | 索引 |
table joins |
| 表连接、MongoDB不支持 |
primary key | primary key | 主键、MongoDB自动将_id字段设置为主键 |
安装 MongoDB
具体因版本不同,不宜赘述,最好参考官方文档。
连接 MongoDB 数据库
连接数据库前你需要确认:
你已经成功安装MongoDB,并启动了MongoDB服务。
你将MongoDB安装目录下的 bin
文件夹路径添加到了环境变量中。
在 cmd 中输入 mongo ,回车。然后就可以看到MongoDB shell 形式的客户端。
MongoDB shell 中使用命令
MongoDB shell 支持JS语法,可直接书写JS语句。
- > stu = {
- ... name: 'jhon',
- ... age:21}
- { "name" : "jhon", "age" : 21 }
- > db.students.insert(stu)
- WriteResult({ "nInserted" : 1 })
- > db.students.insert({name: 'Amy'})
查询
- > db.students.find()
- { "_id" : ObjectId("5ba9dfb9e840eb1e9186871e"), "name" : "jhon", "age" : 21 }
- > db.students.findOne()
- {
- "_id" : ObjectId("5ba9dfb9e840eb1e9186871e"),
- "name" : "jhon",
- "age" : 21
- }
"_id"是MongoDB默认增加的,用来唯一标识一个文档
修改
- > db.students.update({name: 'jhon'},{name: 'jhonc'})
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- > db.students.findOne()
- { "_id" : ObjectId("5ba9dfb9e840eb1e9186871e"), "name" : "jhonc" }
- 可以看到 age 属性也没有了。
- > stu_obj = db.students.findOne({name: "Amy2"})
- {
- "_id" : ObjectId("5ba9e3eee840eb1e91868720"),
- "name" : "Amy2",
- "age" : 16,
- "sex" : "male"
- }
- > stu_obj.name = "Jhon2"
- Jhon2
- > db.students.update({name: "Amy2"}, stu_obj)
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
- > stu_obj = db.students.findOne({name: "Amy2"})
- null
- > stu_obj = db.students.findOne({name: "Jhon2"})
- {
- "_id" : ObjectId("5ba9e3eee840eb1e91868720"),
- "name" : "Jhon2",
- "age" : 16,
- "sex" : "male"
- }
删除
- > db.students.remove({name: "Jhon2"})
- 删除单条
- > db.students.remove({ })
- 清空
使用Python操作MongoDB数据库
安装 pymongo
- from pymongo import MongoClient
- import datetime
- # 连接数据库
- client = MongoClient() # 会连接到默认地址和端口,即 127.0.0.1:27017
- # # 也可以写成这样
- # client = MongoClient('localhost', 27017)
- # client = MongoClient('mongodb://localhost:27017/')
-
- # 创建数据库
- db = client.test_database # 创建名叫 test_database 的数据库
- # # db = client['test-database']
-
- # 增加文档
- # 创建一条文档
- post = {"author": "Mike",
- "text": "My first blog post!",
- "tags": ["mongodb", "python", "pymongo"],
- "date": datetime.datetime.utcnow()}
- # 将post添加到数据库,并获得"_id"
- post_id = db.posts.insert_one(post).inserted_id