Relational Databases
RDBMS(Relational Database Management System):数据库模式中的每个表都有唯一的名称,并定义了其所存储数据的结构,包括:
- 数据类型:Data types of the data columns
- 关系:Relationships between tables
- Constraints:Primary keys/Foreign keys
RDBMS的局限性:
- Schema固定,没法快速修改结构,也不能按需设置动态字段
- 以来vertical scaling数据量增长是需要扩展单一服务器,centralized而非distributed
NoSQL Databases
代表”Not Only SQL”,而不是“No SQL”,是一类无schema的数据库系统,具有horizontal scalability,代表其可以将数据distribute到多台服务器上,其支持多种不同的数据类型(如图片等) 如:MongoDB 是一个开源、面向文档的数据库,设计时兼顾了可扩展性和开发者的灵活性。 与关系数据库中将数据存储在表和行中不同,MongoDB 中你存储的是带有动态模式(无模式、无模式)的 JSON 文档。
CRUD Operations in MongoDB
create
//Create database
db.createCollection("posts") //显式创建:直接创建一个空集合
db.posts.insertOne({"title":"post 1"}) //隐式创建:向不存在的集合中插入item时,会自动创建一个集合
show collections //查看所有collections
//Create document
//插入单个文档
db.posts.insertOne(
{
"title": "Post 1 Title",
"author": "Author 1",
"content": "Content of post 1",
"tags": ["tag1", "tag2"]
}
)
//插入多个文档
db.posts.insertMany([
{
"title": "Post 1 Title",
"author": "Author 1",
"content": "Content of post 1",
"tags": ["tag1", "tag2"]
},
{
"title": "Post 2 Title",
"author": "Author 2",
"content": "Content of post 2",
"tags": ["tag3", "tag4"]
},
{
"title": "Post 3 Title",
"author": "Author 3",
"content": "Content of post 3",
"tags": ["tag1", "tag5"]
}
])read
//查找所有文档
db.posts.find()
db.posts.find({"author": "Author 1"})
db.posts.find({
"author": "Author 1",
"tags": "tag1"
})
//查找单个文档
db.posts.findOne({"title": "Post 1 Title"})
//查找并返回指定字段/定义Projection参数
db.posts.find(
{"author": "Author 1"},
{"title": 1, "author": 1, "_id": 0} //只返回title和author字段,不返回_id
)Update
//更新单个文档
db.posts.updateOne(
{"title": "Post 1 Title"},
{$set: {"author": "New Author"}}
)
//更新多个文档
db.posts.updateMany(
{"author": "Author 1"},
{$set: {"status": "updated"}}
)
//替换整个文档
db.posts.replaceOne(
{"title": "Post 1 Title"},
{
"title": "New Post Title",
"author": "New Author",
"content": "Updated content of the post",
"tags": ["updated", "new", "post"],
"date": new Date(),
"views": 150
}
)Delete
//删除单个文档
db.posts.deleteOne({"title": "Post 1 Title"})
//删除多个文档
db.posts.deleteMany({"author": "Author 1"})
//删除所有文档
db.posts.deleteMany({})
//删除整个集合
db.posts.drop() //删除整个集合及其索引
//查找并删除
db.posts.findOneAndDelete({"title": "Post to Delete"})