MongoDB 是一个高性能,开源,无模式的文档型数据库,是当前noSql数据库产品中最热门的一种。它在许多场景下用于替代传统的关系型数据库或键值对存储方式,MongoDB是用C++开发,MongoDB的官方网址:https://www.mongodb.com/
关于MongoDB
什么是 MongoDB? | 一个以 JSON 为数据模型的文档数据库。 |
---|---|
为什么叫文档数据库? | 文档来自于“JSON Document”,并非我们一般理解的 PDF,WORD 文档。 |
谁开发 MongDB? | 上市公司 MongoDB Inc. ,总部位于美国纽约。 |
主要用途 | 应用数据库,类似于 Oracle, MySQL 海量数据处理,数据平台。 |
主要特点 | 建模为可选 JSON 数据模型比较适合开发者 横向扩展可以支撑很大数据量和并发 |
MongoDB 是免费的吗? | MongoDB 有两个发布版本:社区版和企业版。 社区版是基于 SSPL,一种和 AGPL 基本类似的开源协议 。 企业版是基于商业协议,需付费使用。 |
MongoDB版本的变迁
0.x: 起步阶段 (2008)
1.x: 支持复制集 和分片集 (2010)
2.x: 更丰富的数 据库功能 (2012)
3.x: WiredTiger 和周边生态环境 (2014)
4.x: 分布式事务 支持 (2018)
MongoDB vs. 关系型数据库
MongoDB | RDBMS(关系数据库管理系统) | |
---|---|---|
数据模型 | 文档模型 | 关系模型 |
数据库类型 | OLTP | OLTP |
CRUD 操作 | MQL/SQL | SQL |
高可用 | 复制集 | 集群模式 |
横向扩展能力 | 通过原生分片完善支持 | 数据分区或者应用侵入式 |
索引支持 | B-树、全文索引、地理位置索引、多键(multikey) 索引、TTL 索引 | B树 |
开发难度 | 容易 | 困难 |
数据容量 | 没有理论上限 | 千万、亿 |
扩展方式 | 垂直扩展+水平扩展 | 垂直扩展 |
MongoDB特点及优势
- 开发效率
- 自然模型
- 横向扩展
安装MongoDB
1. 本地安装合适的OS版本
地址:https://www.mongodb.com/download-center/community
如果是Linux系统:
$ mkdir -p /data /data/db
$ cd /data
$ curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.2.3.tgz $ tar -xvf mongodb-linux-x86_64-rhel70-4.2.3.tgz
$ export PATH=$PATH:/data/mongodb-linux-x86_64-rhel70-4.2.3/bin
$ mongod --dbpath /data/db --port 27017 --logpath /data/db/mongod.log --fork –bind_ip 0.0.0.0
如果是MacOS:
brew tap mongodb/brew
brew install mongodb-community@4.2
- the configuration file (
/usr/local/etc/mongod.conf
) - the
log directory path
(/usr/local/var/log/mongodb
) - the
data directory path
(/usr/local/var/mongodb
)
如何启动:
brew services start mongodb-community@4.2
或者
mongod --config /usr/local/etc/mongod.conf --fork
查看:
ps aux | grep -v grep | grep mongod
2. 使用Atlas免费账号
-
官方提供的云托管 MongoDB (https://cloud.mongodb.com/)
-
提供一个终身免费测试账号
-
步骤:
1)注册账号 2)创建免费集群 3)按照提示完成创建并获得连接串 4)使用 mongo 命令行连接集群
MongoDB基本操作
使用insert完成插入操作
操作格式:
db.<集合>.insertOne(<JSON对象>)
db.<集合>.insertMany([<JSON 1>, <JSON 2>, ...<JSON n>])
示例:
db.fruit.insertOne({name: "apple"})
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])
使用 find 查询文档
关于find:
- find 是 MongoDB 中查询数据的基本指令,相当于 SQL 中的 SELECT 。
- find 返回的是游标。
find示例:
db.movies.find( { "year" : 1975 } ) //单条件查询
db.movies.find( { "year" : 1989, "title" : "Batman" } ) //多条件and查询
db.movies.find( { $and : [ {"title" : "Batman"}, { "category" : "action" }] } ) // and的另一种形式
db.movies.find( { $or: [{"year" : 1989}, {"title" : "Batman"}] } ) //多条件or查询
db.movies.find( { "title" : /^B/} ) //按正则表达式查找
查询条件对照表
SQL | MQL |
---|---|
a=1 | {a: 1} |
a <> 1 | {a: {$ne: 1}} |
a>1 | {a: {$gt: 1}} |
a >= 1 | {a: {$gte: 1}} |
a<1 | {a: {$lt: 1}} |
a <= 1 | {a: {$lte: 1}} |
查询逻辑对照表
SQL | MQL |
---|---|
a = 1 AND b = 1 | {a: 1, b: 1}或{$and: [{a: 1}, {b: 1}]} |
a = 1 OR b = 1 | {$or: [{a: 1}, {b: 1}]} |
a IS NULL | {a: {$exists: false}} |
a IN (1, 2, 3) | {a: {$in: [1, 2, 3]}} |
查询逻辑运算符
- $lt: 存在并小于
- $lte: 存在并小于等于
- $gt: 存在并大于
- $gte: 存在并大于等于
- $ne: 不存在或存在但不等于
- $in: 存在并在指定数组中
- $nin: 不存在或不在指定数组中
- $or: 匹配两个或多个条件中的一个
- $and: 匹配全部条件
使用 find 搜索子文档
find 支持使用“field.sub_field”的形式查询子文档。
db.fruit.insertOne({
name: "apple",
from: {
country: "China", province: "Guangdon"
}
})
db.fruit.find( { "from.country" : "China" } )
{ "_id" : ObjectId("5e6764e764b0cc447c446de7"), "name" : "apple", "from" : { "country" : "China", "province" : "Guangdon" } }
使用 find 搜索数组
db.fruit.insert([
{ "name" : "Apple", color: ["red", "green" ] },
{ "name" : "Mango", color: ["yellow", "green"] }
])
db.fruit.find({color: "red"})
{ "_id" : ObjectId("5e67624564b0cc447c446de4"), "name" : "Apple", "color" : [ "red", "green" ] }
db.fruit.find({$or: [{color: "red"}, {color: "yellow"}]} )
{ "_id" : ObjectId("5e67624564b0cc447c446de4"), "name" : "Apple", "color" : [ "red", "green" ] }
{ "_id" : ObjectId("5e67624564b0cc447c446de5"), "name" : "Mango", "color" : [ "yellow", "green" ] }
使用 find 搜索数组中的对象
db.movies.insertOne( {
"title": "Raiders of the Lost Ark",
"filming_locations": [
{ "city" : "Los Angeles", "state" : "CA", "country" : "USA"},
{ "city" : "Rome", "state" : "Lazio", "country" : "Italy" },
{ "city" : "Florence", "state" : "SC", "country" : "USA" }
]
})
db.movies.find({"filming_locations.city": "Rome"})
{ "_id" : ObjectId("5e67637564b0cc447c446de6"), "title" : "Raiders of the Lost Ark", "filming_locations" : [ { "city" : "Los Angeles", "state" : "CA", "country" : "USA" }, { "city" : "Rome", "state" : "Lazio", "country" : "Italy" }, { "city" : "Florence", "state" : "SC", "country" : "USA" } ] }
db.getCollection('movies').find({ "filming_locations.city": "Rome","filming_locations.country": "USA"})
{ "_id" : ObjectId("5e67637564b0cc447c446de6"), "title" : "Raiders of the Lost Ark", "filming_locations" : [ { "city" : "Los Angeles", "state" : "CA", "country" : "USA" }, { "city" : "Rome", "state" : "Lazio", "country" : "Italy" }, { "city" : "Florence", "state" : "SC", "country" : "USA" } ] }
db.getCollection('movies').find({
"filming_locations": { $elemMatch:{"city":"Rome", "country": "USA"}
} })
无结果
控制 find 返回的字段
- find 可以指定只返回指定的字段;
- _id字段必须明确指明不返回,否则默认返回;
- 在 MongoDB 中我们称这为投影(projection);
- db.movies.find({“category”: “action”},{"_id":0, title:1});0表示不返回
使用 remove 删除文档
- remove 命令需要配合查询条件使用;
- 匹配查询条件的的文档会被删除;
- 指定一个空文档条件会删除所有文档;
一下示例:
b.testcol.remove( { a : 1 } ) // 删除a 等于1的记录
db.testcol.remove( { a : { $lt : 5 } } ) // 删除a 小于5的记录
db.testcol.remove( { } ) // 删除所有记录
db.testcol.remove() //报错
使用 update 更新文档
-
Update 操作执行格式: db.<集合>.update(<查询条件>, <更新字段>)
-
使用 updateOne 表示无论条件匹配多少条记录,始终只更新第一条;
-
使用 updateMany 表示条件匹配多少条就更新多少条;
-
updateOne/updateMany 方法要求更新条件部分必须具有以下之一,否则将报错:
$set/$unset $push/$pushAll/$pop $pull/$pullAll $addToSet
-
示例:
db.fruit.insertMany([ {name: "apple"}, {name: "pear"}, {name: "orange"} ]) db.fruit.updateOne({name: "apple"}, {$set: {from: "China"}})
使用 update 更新数组
- $push: 增加一个对象到数组底部
- $pushAll: 增加多个对象到数组底部
- $pop: 从数组底部删除一个对象
- $pull: 如果匹配指定的值,从数组中删除相应的对象
- $pullAll: 如果匹配任意的值,从数据中删除相应的对象
- $addToSet: 如果不存在则增加一个值到数组
使用 drop 删除集合
-
使用 db.<集合>.drop() 来删除一个集合
-
集合中的全部文档都会被删除
-
集合相关的索引也会被删除
db.colToBeDropped.drop()
使用 dropDatabase 删除数据库
-
使用 db.dropDatabase() 来删除数据库
-
数据库相应文件也会被删除,磁盘空间将被释放
use tempDB
db.dropDatabase()
show collections // No collections show dbs // The db is gone
参考:
Install MongoDB Community Edition on macOS
「真诚赞赏,手留余香」
请我喝杯咖啡?
使用微信扫描二维码完成支付
