MongoDB入门
MongoDB是一个文档数据库,MongoDB中的记录是一个文档,它是由键值对({'字段':'值'})组成的数据结构。类似于JSON对象。字段的值可以包括其他文档,数组和文档数组。
使用文档的优点是:
-
文档(即对象)对应于许多编程语言中的内置数据类型。
-
嵌入式文档和数组减少了对昂贵连接的需求。
-
动态模式支持流畅的多态性。
数据库操作
连接
mongodb://[username:password@]host1
库创建和使用
use dbName
查看
- show dbs 显示所有库
- show logs 显示系统日志
- show collections 显示当前库下的所有集合
- show profile 显示系统性能监控
- show users 显示所有用户
- show roles 显示所有角色
删除库
db.dropDatabase()
集合
创建
db.createCollections('dbName',{capped:bol,size:num,max:num})
- capped:是否为固定集合
- size:固定集合的大小,单位字节
- max:最大的文档数(超过时,新的顶掉旧的)
删除
db.collectionName.drop()
文档
插入
- db.collectionName.insert(document or [documents],options):插入一个或者多个文档 (不推荐)
- db.collectionName.insertOne(document,options):只能插入一个文档
- db.collectionName.insertMany([documents],options):插入多个文档
options
- writeConcern:要求确认写操作,是:1,否:0
- ordered:是否按序写入,是:true,否:false
其他方法
- db.collection.save()
- db.collection.()
与upsert: true选项一起使用
- db.collection.() (不推荐)
- db.collection.()
- db.collection.()
- db.collection.findAndModify()
- db.collection.findOneAndUpdate()
- db.collection.findOneAndReplace()
查询
- db.collectionName.find({}) 查询集合中所有的文档
- db.collectionName.find(
,projection) :指定查询条件 - projection:指定返回的字段,为1就返回
例子:db.inventory.find({"item":"journal"},{"item":1,"qty":1})
比较
-
等于:db.collectionName.find({"field":"value"})
-
小于:db.collectionName.find({"field":{$lt:"value"})
-
小于等于:db.collectionName.find({"field":{$lte:"value"})
-
大于:db.collectionName.find({"field":{$gt:"value"})
-
大于等于:db.collectionName.find({"field":{$gte:"value"})
-
不等于:db.collectionName.find({"field":{$ne:"value"})
-
值在列表中:db.collectionName.find({"field":{$in:["value1","value2]"})
AND
db.collectionName.find({"field1":"value1","field2":"value2"})
OR
db.collectionName.find($or:[{"field1":"value1","field2":"value2"}])
$type字段类型操作符
| 类型 | 对应数字 |
|---|---|
| Double | 1 |
| String | 2 |
| Object | 3 |
| Array | 4 |
| Binary data | 5 |
| Object id | 7 |
| Boolean | 8 |
| Date | 9 |
| Null | 10 |
| Regular Expression | 11 |
| JavaScript | 13 |
| Symbol | 14 |
| JavaScript (with scope) | 15 |
| 32-bit integer | 16 |
| Timestamp | 17 |
| 64-bit integer | 18 |
| Min key | 255 |
| Max key | 127 |
例子:db.collectionName.find({"field" : {$type : 2}})=>db.collectionName.find({"field" : {$type : 'string'}})
建议使用字符串,比较直观
skip和limit和排序
- db.collectionName.find().limit(num) # 指定数量的数据
- db.collectionName.find().skip(num) # 跳过指点数量的数据
- db.collectionName.find().sort("field":1) # 1为正序,-1为逆序
更新
- db.collectionName.update(
, , ):更新单个或多个匹配的文档 (不推荐) - db.collectionName.updateOne(
, , ):更新单个匹配的文档 - db.collectionName.updateMany(
, , ):更新多个匹配的文档
<filter>
过滤条件,比如:
- {"filed1":"value1","filed2":"value2"}
- {"filed":{$lt:50}}
<update>
更新操作
- $set,对字段设置新的值
- $currentDate,设置当前日期
例子:
db.collectionName.updateOne(
{"field":"value"},
{
$set:{"field1":"newValue"},
$currentDate:{lastModified:true} # 会添加更新最近修改时间的字段
}
)
<options>
- upsert : 若不存在update的记录,是否插入,true为插入,默认是false,不插入。
- multi : 默认是false,只更新找到的第一条记录,若为true,就把按条件查出来多条记录全部更新。
- writeConcern :可选,抛出异常的级别。
其他方法
- db.collectionName.save()
- db.collectionName.replaceOne()
- 与updateOne()的区别是:
- updateOne只修改文档下指定字段的值,其他字段的值不变
- replaceOne除了指定字段的值会修改之外,其他字段若为空也会直接以空覆盖
删除
- db.collectionName.deleteOne(
):删除匹配的第一个 - db.collectionName.deleteMany(
):删除匹配的多个 - db.collectionName.deleteMany({}):删除集合中的所有数据
其他方法
- db.collectionName.remove() (不推荐)
- db.collectionName.findeOneAndDelelte()
- db.collectionName.findOneAndModify({remove:true})
批量写入操作
有序vs无序
有序:MongoDB串行地执行操作,{ordered:true}
无序:MongoDB并行地执行操作,{ordered:false}
支持:insertOne,updateOne,updateMany,replaceOne,deleteOne,deleteMany
使用
db.collectionName.bulkwrite([
{insertOne:{
"document":{"field":"value"}
}
},
{updateOne:{
"filter":{"field":"value"},
"update":{$set:{"field":"value:}},
}
},
{deleteOne:{
"filter":{"field":"value"}
}
},
{replaceOne:{
"filter":{"field":"value"},
"replacement":{"field1":"value1","field2":"value2","field3":"value3",...} # 最好是所有字段的值都修改,否则会被空覆盖
}
}
])
可重试写入/读取
可重试写入允许MongoDB驱动程序在遇到网络错误或在复制集或分片群集中找不到正常的主操作时自动重试特定的写或者读操作一次。
连接mongodb的字符串的选项中添加:
-
retryWrites:false,默认为true
-
retryReads:false,默认为true
文本搜索
使用$text查询操作符对具有文本索引的集合执行文本索引。
$text将使用空格和大多数标点作为分隔符对搜索字符串进行标记,并在搜索字符串中对所有这些标记执行逻辑或操作。
例子
- db.collectionName.find( { $text: { $search: "java coffee -shop" } } ) # 查找包含“coffee”和“java”列表中任何一个单词以及不包含”shop“的结果
- db.collectionName.find( { $text: { $search: "\"coffee shop\"" } } ) # 查找包含“coffee shop”短语的结果
- db.collectionName.find( { $text: { $search: "java coffee shop" } }, { score: { $meta: "field" } } # 指定结果匹配的相关性 ).sort( { score: { $meta: "field" } } ) # 根据匹配相关性排序
视图
创建
- db.createCollection( "viewName", { "viewOn" : "collectionName or viewName", "pipeline" : [{condition},{condition},...], "collation" : { {...}.sort('field':1 or -1) } } )
- db.createView( "viewName", "collectionName or viewName", [{condition},{condition},...], { "collation" : { {...}.sort('field':1 or -1)} } )
例子:
db.createView( "viewName", "collectionName", [ { $lookup: { from: "shipping", localField: "orderNo", foreignField: "orderNo", as: "shipping" } }, { $project: { "orderNo": 1, "price": 1, "shipping.address": 1 } } ] )
db.viewName.find({}) # 便可查询视图
collation
排序的规则,包含的字段
{ locale:
很多时候排序可以在pipeline中实现,所以collation会使用得较少
查看
- db.getCollectionInfo('name':'collectionName') # 根据条件查看集合属性
- db.getCollectionNames('collectionName') # 根据名称查看集合
修改
db.runCommand({
collMod:"viewName",
viewOn:"fieldName",
pipeline:[{condition},{condition},...]
})
也可以删除视图后在创建一个新的视图
删除
db.viewName.drop()
视图是只读的,以下为支持视图的读操作:
- db.collection.find()
- db.collection.findOne()
- db.collection.aggregate()
- db.collection.count()
- db.collection.distinct