mongoDB
mongo 命令
MongoDB shell version v4.4.15
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.168.0.5/foo foo database on 192.168.0.5 machine
192.168.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
mongodb://192.168.0.5:9999/foo connection string URI can also be used
Options:
--ipv6 enable IPv6 support (disabled by
default)
--host arg server to connect to
--port arg port to connect to
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no
'db address' arg expected
--norc will not run the ".mongorc.js" file on
start up
--quiet be less chatty
--eval arg evaluate javascript
--disableJavaScriptJIT disable the Javascript Just In Time
compiler
--enableJavaScriptJIT enable the Javascript Just In Time
compiler
--disableJavaScriptProtection allow automatic JavaScript function
marshalling
--retryWrites automatically retry write operations
upon transient network errors
--disableImplicitSessions do not automatically create and use
implicit sessions
--jsHeapLimitMB arg set the js scope's heap size limit
--idleSessionTimeout arg (=0) Terminate the Shell session if it's been
idle for this many seconds
TLS Options:
--tls use TLS for all connections
--tlsCertificateKeyFile arg PEM certificate/key file for TLS
--tlsCertificateKeyFilePassword arg Password for key in PEM file for TLS
--tlsCAFile arg Certificate Authority file for TLS
--tlsCRLFile arg Certificate Revocation List file for TLS
--tlsAllowInvalidHostnames Allow connections to servers with
non-matching hostnames
--tlsAllowInvalidCertificates Allow connections to servers with
invalid certificates
--tlsFIPSMode Activate FIPS 140-2 mode at startup
--tlsDisabledProtocols arg Comma separated list of TLS protocols to
disable [TLS1_0,TLS1_1,TLS1_2]
FLE AWS Options:
--awsAccessKeyId arg AWS Access Key for FLE Amazon KMS
--awsSecretAccessKey arg AWS Secret Key for FLE Amazon KMS
--awsSessionToken arg Optional AWS Session Token ID
--keyVaultNamespace arg database.collection to store encrypted
FLE parameters
--kmsURL arg Test parameter to override the URL for
KMS
AWS IAM Options:
--awsIamSessionToken arg AWS Session Token for temporary
credentials
Authentication Options:
-u [ --username ] arg username for authentication
-p [ --password ] arg password for authentication
--authenticationDatabase arg user source (defaults to dbname)
--authenticationMechanism arg authentication mechanism
--gssapiServiceName arg (=mongodb) Service name to use when authenticating
using GSSAPI/Kerberos
--gssapiHostName arg Remote host name to use for purpose of
GSSAPI/Kerberos authentication
file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified
mongo 连接
mongo -p password -u username
databases 基础命令
查看当前数据库:db
查看所有数据库:show dbs/show databases
切换数据库:use db_name
删除当前数据库:db.dropDatabase()
手动创建集合:
db.createCollection(name,options)
db.createCollection("stu")
db.createCollection("sub", {capped: true, size: 10})
参数capped:默认值为false表示不设置上限,值为true表示设置上限
参数size:当capped 值为true时,需要指定此参数,表示上限大小,当文件达到上限是,会将之前的数据覆盖
查看集合:show collections
删除集合:db.collection_name.drop()
创建日期语句:new Date("2021-07-07")
参数格式:YYYY-MM-DD
新增数据
字段插入:
db.collection_name.insert({"name": "zhangsan", "age": 18})
db.collection_name.save({"name": "zhangsan", "age": 18})
两个区别,insert如果插入数据_id已存在,则报错。
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test1.test1 index: _id_ dup key: { : \"101\" }"
}
})
save如果插入数据_id已存在,则覆盖原来数据
数据查询:
db.collection_name.find() 会查询集合下的所有元素
db.collection_name.find({条件文档})
db.collection_name.findOne({条件文档}) 查询只返回一个
db.collection_name.find({条件文档}).pretty()
> db.test1.find({"name": "zhangsan1"})
{ "_id" : ObjectId("60e56aa72b2a0b777e5a1102"), "name" : "zhangsan1", "age" : 20 }
{ "_id" : "101", "name" : "zhangsan1", "age" : 30 }
{ "_id" : ObjectId("60e56b992b2a0b777e5a1103"), "name" : "zhangsan1", "age" : 20 }
> db.test1.findOne({"name": "zhangsan1"})
{
"_id" : ObjectId("60e56aa72b2a0b777e5a1102"),
"name" : "zhangsan1",
"age" : 20
}
> db.test1.find({"name": "zhangsan1"}).pretty()
{
"_id" : ObjectId("60e56aa72b2a0b777e5a1102"),
"name" : "zhangsan1",
"age" : 20
}
{ "_id" : "101", "name" : "zhangsan1", "age" : 30 }
{
"_id" : ObjectId("60e56b992b2a0b777e5a1103"),
"name" : "zhangsan1",
"age" : 20
}
数据更新
db.collection_name.update(, , {multi: })
query:查询条件
update:更新操作符
multi:可选,默认false,表示只更新找到第一条记录,true表示把满足条件的文档全部更新。
例:
db.collect_name.update({"name": "hr"}, {"name": "mnc"}) 更新一条
会将满足条件内容替换成后面内容
更新前:{ "_id" : ObjectId("60e56a9e2b2a0b777e5a1101"), "name" : "zhangsan", "age" : 18 }
> db.test1.update({"name": "zhangsan"}, {"name": "lisi"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test1.find()
更新后:{ "_id" : ObjectId("60e56a9e2b2a0b777e5a1101"), "name" : "lisi" }
db.collect_name.update({"name": "hr"}, {$set: {name: "hys"}}) 更新一条
$set: 只替换对应键的值
更新前:{ "_id" : ObjectId("60e572b22b2a0b777e5a1104"), "name" : "zhangsan2", "age" : 20 }
> db.test1.update({"name": "zhangsan2"}, {$set:{"name": "lisi2"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
更新后:{ "_id" : ObjectId("60e572b22b2a0b777e5a1104"), "name" : "lisi2", "age" : 20 }
db.collect_name.update({}, {$set:{gender: 0}}, {multi: true}) 更新全部
数据删除
db.collection_name.remove(, {justOne: })
参数query:可选,删除文档的条件
参数justOne:可选,如果设为true或1,则只删除一条,默认false,表示删除多条。
数据类型:
object ID:文档ID
相当于MySQL中的主键,保证文档的唯一性。可以自己设置,如果插入数据没有提供那么会自动生成一个独特的_id,
objectID是一个12字节的十六进制数:
前4个字节为当前时间戳
之后3个字节是机器ID
接下来两个字节是MongoDB的服务进程id
最后3个字节是简单的增量值
string:字符串,最常用,必须是有效的UTF-8
boolean:存储一个布尔值,true/false
integer:整数可以是32/64,这取决于服务器
double:存储浮点型
arrays:数据或列表,多个值存储到一个键
object:用于嵌入式的文档,即一个值为一个文档
null:存储null值
timestamp:时间戳
date:存储当前时间的UNIX时间格式。
- 总结:与json数据类型相似。
运算符
比较运算符
等于:默认是等于判断,没有运算符
小于:$lt (less than)
小于等于:$lte (less than equal)
大于:$gt (greater than)
大于等于:$gte (greater than equal)
不等于:$ne
db.stu.find({"age": {$gte: 18}})
范围运算符
$in,$nin 判断是否在某个范围内
查询年龄18, 28的学生:db.stu.find({"age": {$in: [18, 28]}})
逻辑运算符
and:直接在json文档中写多个条件
查询年龄大于等于18,并且性别为true的学生
db.stu.find({age: {$gte: 18}, gender: true})
or:使用$or,值为数组,数组中元素为json
查询年龄大于18,或者性别为false的学生
db.stu.find({$or: [{age: {$gt: 18}}, {gender: false}]})
查询年龄大于18或性别为true,并且姓名是gj
db.stu.find({$or: [{age: {$gt: 18}}, {gender: true}], name: "gj"})
正则表达式
使用// 或 $regex 编写正则表达式
查询sku键以abc开头的值对应的数据:db.collect_name.find({sku: /^abc/})
查询sku键以789结尾的值对应的数据:db.collect_name.find({sku: {$regex: '789$'}})
limit、skip
limit():用于读取指定数量的文档
db.collect_name.find().limit(number)
查询前2条学生记录
db.stu.find().limit(2)
skip():用于跳过指定数量的文档,取之后的数据
db.collect_time.find().skip(number)
查询前两条之后的数据
db.collect_time.find().skip(2)
同时使用:
db.collect_time.find().limit(2).skip(3)
等价
db.collect_time.find().skip(3).limit(2)
注意:当需要limit,skip同时使用时,如果查询的集合元素数据量很大的情况下,应该先skip,之后在limit
数据某个key是否存在
# 查询 base_infos --> 中 full_name 不存在 key 的数据
db.base_infos.find({"full_name": {$exists: false}})
自定义查询
使用$where 后面写一个函数,返回满足条件的数据
查询年龄大于30的学生
db.stu.find({$where: function(){return this.age > 30;}})
查询投影
只需要返回指定字段,默认不写,返回全部字段
db.collect_name.find({条件}, {字段名称1: 1,....})
返回符合条件的数据,其中返回字段有_id,字段名称1
特殊:如果返回不包含_id,则需要给_id=0。
注意:字段名称为0,只对_id有效,其他字段置0会报错。
如果没有条件,需要查询全部,则条件为空{},如果不写则默认第一个为条件,不会产生查询投影,只返回指定字段。
> db.test1.find({name: "zhangsan1"})
{ "_id" : ObjectId("60e56aa72b2a0b777e5a1102"), "name" : "zhangsan1", "age" : 20 }
{ "_id" : "101", "name" : "zhangsan1", "age" : 30 }
{ "_id" : ObjectId("60e56b992b2a0b777e5a1103"), "name" : "zhangsan1", "age" : 20 }
> db.test1.find({name: "zhangsan1"}, {name:1})
{ "_id" : ObjectId("60e56aa72b2a0b777e5a1102"), "name" : "zhangsan1" }
{ "_id" : "101", "name" : "zhangsan1" }
{ "_id" : ObjectId("60e56b992b2a0b777e5a1103"), "name" : "zhangsan1" }
> db.test1.find({name: "zhangsan1"}, {name:1, _id: 0})
{ "name" : "zhangsan1" }
{ "name" : "zhangsan1" }
{ "name" : "zhangsan1" }
> db.test1.find({name: "zhangsan1"}, {name:1, age: 0})
Error: error: {
"ok" : 0,
"errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
"code" : 2,
"codeName" : "BadValue"
}
创建索引
默认情况下索引字段的值可以相同
db.collect_name.ensureIndex({属性: 1}),1表示升序;-1表示降序
测试:插入10w条数据到数据库中
for(i=0;i<100000;i++){db.test2.insert({name: 'test' + i, age: i})}
创建索引之前:
db.test2.find({name: 'test90000'})
db.test2.find({name: 'test90000'}).explain('executionStats')
创建索引后:
db.test2.find({name: 'test90000'})
db.test2.find({name: 'test90000'}).explain('executionStats')
创建唯一索引
unique=true
创建唯一索引之前,应该保证对应字段不重复。否则创建索引失败。
db.collection_name.ensureIndex({name: 1}, {unique: true})
创建联合索引
db.collection_name.ensureIndex({name: 1, age: 1})
查看当前集合的所有索引
db.collection_name.getIndexes()
删除索引
db.collection_name.dropIndex('索引名称')
数据备份和恢复
数据备份
mongodump -h dbhost -d dbname -o dbdirectory
-h:服务器地址,可以指定端口号
-d:需要备份的数据库名称
-o:备份的数据存放位置,此目录存放着备份出来的数据
例:
mongodump -h 192.168.0.1:27017 -d test1 -o ~/Desktop/test1bak
数据恢复
mongorestore -h dbhost -d dbname --dir dbdirectory
-h:服务器地址,可以指定端口号
-d:需要恢复的数据库名称
--dir:备份的数据存放位置
例:
mongorestore -h 192.168.0.1:27017 -d test1 --dir ~/Desktop/test1bak/test