> use cisco
switched to db cisco
> db
cisco
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> db.mytest.insert({'name':'liu'})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
cisco 0.000GB
config 0.000GB
local 0.000GB
> db.dropDatabase()
{ "dropped" : "cisco", "ok" : 1 }
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> db.stats()
{
"db" : "test", #数据库名称
"collections" : 0, #集合数量
"views" : 0,
"objects" : 0, #文档对象的个数,所有集合的记录数之和
"avgObjSize" : 0, #平均每个对象的大小
"dataSize" : 0, #当前库所有集合的数据大小
"storageSize" : 0, #磁盘存储大小
"numExtents" : 0, #所有集合的扩展数据量统计数
"indexes" : 0, #已建立索引数量
"indexSize" : 0,
"scaleFactor" : 1,
"fileSize" : 0,
"fsUsedSize" : 0,
"fsTotalSize" : 0,
"ok" : 1
}
> db.getCollectionNames()
[ ]
> use test
switched to db test
> db.mytest.insert({'name':'liu'})
WriteResult({ "nInserted" : 1 })
> db.getCollectionNames()
[ "mytest" ]
查看集合(两种方法皆可)
> use test
switched to db test
> show collections
books
mytest
> show tables
books
mytest
删除集合
> db.mytest.drop()
true
>show collections
books
语法:db.collection.insert({"键名1":值1,"键名2":值2...})
> use test
switched to db test
> db.books.insert(
... {name:"C语言编程",
... price:32
... }
... )
WriteResult({ "nInserted" : 1 })
> db.books.insert({name:"Python入门",price:48})
WriteResult({ "nInserted" : 1 })
> db.books.find()
{ "_id" : ObjectId("6274cfa1acc235794634012b"), "name" : "C语言编程", "price" : 32 }
{ "_id" : ObjectId("6274cfd6acc235794634012c"), "name" : "Python入门", "price" : 48 }
# insert命令,自动产生一个_id值
# "_id"是十六进制表示(12B):时间戳(4B)+机器ID(3B)+进程ID(2B)+排序流水号(3B)
# insert命令可以用save命令代替。若给save命令指定_id值,则会更新默认_id值;
# 集合books不存在,则会创建,如存在,则变成多条文档的集合
> db.books.insert(
... [{name:"小学教材",price:20},
... {name:"初中生教材",price:30},
... {name:"高中生教材",price:40}
... ])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
> document=({name:"英文教材",price:49})
{ "name" : "英文教材", "price" : 49 }
> db.books.insert(document)
WriteResult({ "nInserted" : 1 })
>
db.集合名.findOne() #查询一行
db.集合名.find() #查询全部
db.集合名.find().pretty() #格式化打印
db.集合名.find({查找条件}) #按照条件进行查找
> db.books.findOne()
{
"_id" : ObjectId("6274cfa1acc235794634012b"),
"name" : "C语言编程",
"price" : 32
}
> db.books.find().pretty()
{
"_id" : ObjectId("6274cfa1acc235794634012b"),
"name" : "C语言编程",
"price" : 32
}
{
"_id" : ObjectId("6274cfd6acc235794634012c"),
"name" : "Python入门",
"price" : 48
}
{
"_id" : ObjectId("6274d2d0acc235794634012d"),
"name" : "小学教材",
"price" : 20
}
{
"_id" : ObjectId("6274d2d0acc235794634012e"),
"name" : "初中生教材",
"price" : 30
}
{
"_id" : ObjectId("6274d2d0acc235794634012f"),
"name" : "高中生教材",
"price" : 40
}
{
"_id" : ObjectId("6274d351acc2357946340130"),
"name" : "英文教材",
"price" : 49
}
> db.books.find({price:30}).pretty()
{
"_id" : ObjectId("6274d2d0acc235794634012e"),
"name" : "初中生教材",
"price" : 30
}
> db.books.find({price:{$in:[20,30,40]}}).pretty()
{
"_id" : ObjectId("6274d2d0acc235794634012d"),
"name" : "小学教材",
"price" : 20
}
{
"_id" : ObjectId("6274d2d0acc235794634012e"),
"name" : "初中生教材",
"price" : 30
}
{
"_id" : ObjectId("6274d2d0acc235794634012f"),
"name" : "高中生教材",
"price" : 40
}
> db.books.find({price:{$lt:30}})
{ "_id" : ObjectId("6274d2d0acc235794634012d"), "name" : "小学教材", "price" : 20 }
> db.books.find({price:{$lte:30}})
{ "_id" : ObjectId("6274d2d0acc235794634012d"), "name" : "小学教材", "price" : 20 }
{ "_id" : ObjectId("6274d2d0acc235794634012e"), "name" : "初中生教材", "price" : 30 }
> db.books.find({price:{$gt:30}})
{ "_id" : ObjectId("6274cfa1acc235794634012b"), "name" : "C语言编程", "price" : 32 }
{ "_id" : ObjectId("6274cfd6acc235794634012c"), "name" : "Python入门", "price" : 48 }
{ "_id" : ObjectId("6274d2d0acc235794634012f"), "name" : "高中生教材", "price" : 40 }
{ "_id" : ObjectId("6274d351acc2357946340130"), "name" : "英文教材", "price" : 49 }
> db.books.find({price:{$gte:30}})
{ "_id" : ObjectId("6274cfa1acc235794634012b"), "name" : "C语言编程", "price" : 32 }
{ "_id" : ObjectId("6274cfd6acc235794634012c"), "name" : "Python入门", "price" : 48 }
{ "_id" : ObjectId("6274d2d0acc235794634012e"), "name" : "初中生教材", "price" : 30 }
{ "_id" : ObjectId("6274d2d0acc235794634012f"), "name" : "高中生教材", "price" : 40 }
{ "_id" : ObjectId("6274d351acc2357946340130"), "name" : "英文教材", "price" : 49 }
> db.books.find({price:{$ne:30}})
{ "_id" : ObjectId("6274cfa1acc235794634012b"), "name" : "C语言编程", "price" : 32 }
{ "_id" : ObjectId("6274cfd6acc235794634012c"), "name" : "Python入门", "price" : 48 }
{ "_id" : ObjectId("6274d2d0acc235794634012d"), "name" : "小学教材", "price" : 20 }
{ "_id" : ObjectId("6274d2d0acc235794634012f"), "name" : "高中生教材", "price" : 40 }
{ "_id" : ObjectId("6274d351acc2357946340130"), "name" : "英文教材", "price" : 49 }
查询值得固定后一部分
> db.books.find({name:{$regex:/教材$/}}).pretty()
{
"_id" : ObjectId("6274d2d0acc235794634012d"),
"name" : "小学教材",
"price" : 20
}
{
"_id" : ObjectId("6274d2d0acc235794634012e"),
"name" : "初中生教材",
"price" : 30
}
{
"_id" : ObjectId("6274d2d0acc235794634012f"),
"name" : "高中生教材",
"price" : 40
}
{
"_id" : ObjectId("6274d351acc2357946340130"),
"name" : "英文教材",
"price" : 49
}
查询值的固定前一部分
> db.books.find({name:{$regex:/^C语言/}}).pretty()
{
"_id" : ObjectId("6274cfa1acc235794634012b"),
"name" : "C语言编程",
"price" : 32
}
查询值得任意部分
> db.books.find({name:{$regex:/Python/}}).pretty()
{
"_id" : ObjectId("6274cfd6acc235794634012c"),
"name" : "Python入门",
"price" : 48
}
不区大小写
> db.books.find({name:{$regex:/python/i}}).pretty()
{
"_id" : ObjectId("6274cfd6acc235794634012c"),
"name" : "Python入门",
"price" : 48
}
> db.books.find({price:{$gt:15,$lt:35}}).pretty()
{
"_id" : ObjectId("6274cfa1acc235794634012b"),
"name" : "C语言编程",
"price" : 32
}
{
"_id" : ObjectId("6274d2d0acc235794634012d"),
"name" : "小学教材",
"price" : 20
}
{
"_id" : ObjectId("6274d2d0acc235794634012e"),
"name" : "初中生教材",
"price" : 30
}
db.collection.update
> db.order.insert(
... {
... title:"商品购物单1",
... amount:35,
... detail:[
... {name:"苹果",price:22},{name:"面粉",price:18}
... ]
... }
... )
WriteResult({ "nInserted" : 1 })
> db.order.update(
... {title:"商品购物单1"},
... {$set:{title:"商品购物单2"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
----------$inc加法运算,正数,负数,小数----------
> db.order.update(
... {title:"商品购物单2"},
... {$inc:{amount:5}}) $inc加法运算,正数,负数,小数
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find().pretty()
{
"_id" : ObjectId("6274f05eacc2357946340131"),
"title" : "商品购物单2",
"amount" : 40,
"detail" : [
{
"name" : "苹果",
"price" : 22
},
{
"name" : "面粉",
"price" : 18
}
]
}
----------$mul 可以做乘法运算-----------
> db.order.update(
... {title:"商品购物单2"},
... {$mul:{amount:2}}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find().pretty()
{
"_id" : ObjectId("6274f05eacc2357946340131"),
"title" : "商品购物单2",
"amount" : 80,
"detail" : [
{
"name" : "苹果",
"price" : 22
},
{
"name" : "面粉",
"price" : 18
}
]
}
----------$rename 可以修改错误的键名----------
----------$unset删除一个字段----------
> db.order.update( {title:"商品购物单2"}, {$unset:{title:"商品购物单2"}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find().pretty()
{
"_id" : ObjectId("6274f05eacc2357946340131"),
"amount" : 80,
"detail" : [
{
"name" : "苹果",
"price" : 22
},
{
"name" : "面粉",
"price" : 18
}
]
}
> db.order.insert(
... {
... _id:12,
... title:"商品购物单5",
... amount:90,
... unit:"元",
... detail:[
... {name:"葡萄",price:60},{name:"面粉",price:30}
... ],
... ocerview:{shop:"京东电子商务平台",shopno:5,adress:"地球村"}
... }
... )
... ^C
> db.order.insert(
... {
... _id:12,
... title:"商品购物单5",
... amount:90,
... unit:"元",
... detail:[
... {name:"葡萄",price:60},{name:"面粉",price:30}
... ],
... overview:{shop:"京东电子商务平台",shopno:5,address:"地球村"}
... })
WriteResult({ "nInserted" : 1 })
> db.order.update(
... {_id:12},
... {
... $set:{
... "detail.1":{name:"大米",price:40},
... "overview.address":"北京市丰台区南里道15号"
... }
... }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.order.find({_id:12}).pretty()
{
"_id" : 12,
"title" : "商品购物单5",
"amount" : 90,
"unit" : "元",
"detail" : [
{
"name" : "葡萄",
"price" : 60
},
{
"name" : "大米",
"price" : 40
}
],
"overview" : {
"shop" : "京东电子商务平台",
"shopno" : 5,
"address" : "北京市丰台区南里道15号"
}
}
> db.order.update(
{"detail.name":"面粉","detail.price":{$lte:30}},
{
$set:{
"detail.1":{name:"面粉",price:40}
}
},
{multi:true})
db.集合名.remove({查询条件}) # 删除符合条件的文档
db.集合名.remove({}) # 删除全部数据
> db.tests.insertMany( [ {item:"铅笔",price:2}, {item:"钢笔",price:60} ] )
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("627496ba0b5af0d2f5c7d620"),
ObjectId("627496ba0b5af0d2f5c7d621")
]
}
> db.tests.remove({price:{$lt:3}})
WriteResult({ "nRemoved" : 1 })
> db.tests.find().pretty()
{
"_id" : ObjectId("627496ba0b5af0d2f5c7d621"),
"item" : "钢笔",
"price" : 60
}
> db.tests.remove({})
WriteResult({ "nRemoved" : 1 })
> db.tests.find().pretty()
>
> use admin
switched to db admin
> db.createUser(
... {
... user:"admin",
... pwd:"Com.123456",
... roles:[{role: "userAdminAnyDatabase", db: "admin"},"readWriteAnyDatabase" ]
... }
... )
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
"readWriteAnyDatabase"
]
}
> show users
{
"_id" : "admin.admin",
"userId" : UUID("313aeb76-6413-468f-bed2-f16a8ec3f942"),
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
db.adminCommand( { shutdown: 1 }
使用带访问控制的shell命令启动(另起一个终端敲下一条命令)
mongod --auth --port 27017 --dbpath /var/lib/mongo
[root@localhost ~]# vim /etc/mongod.conf
security:
authorization: enabled
[root@localhost ~]#systemctl restart mongod
[root@localhost ~]#mongo --port 27017 --authenticationDatabase "admin" -u
"admin" -p
MongoDB shell version v4.2.2
Enter password:
connecting to: mongodb://127.0.0.1:27017/?
authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("3b80127d-99f8-4b73-8982-
4e2f7a19a8b7") }
MongoDB server version: 4.2.2
> show tables
books
mytest
order
tests
>
[root@localhost mongo
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?
compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("cc7966ec-5b07-45bb-b7d4-
282b6b81b5cd") }
MongoDB server version: 4.2.2
> show tables
Warning: unable to run listCollections, attempting to approximate collection
names by parsing connectionStatus
> use admin
switched to db admin
> db.auth("admin","Com.123456")
1
> show tables
system.users
system.version
> use test
switched to db test
> show tables
books
mytest
order
tests
>
> use test
switched to db test
> db.createUser(
... {
... user:"myTestUser",
... pwd:"Com.123456",
... roles:[
... {role: "readWrite", db: "test" },
... { role: "read", db: "reporting" } ]
... })
Successfully added user: {
"user" : "myTestUser",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "reporting"
}
]
}
[root@localhost ~]# mongo --port 27017 -u "myTester1" --authenticationDatabase "test" -p
MongoDB shell version v5.0.8
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=test&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("21c46e44-a0b5-49c8-8d73-c1e5759bc436") }
MongoDB server version: 5.0.8
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
>
> db.foo.insert( { x: 1, y: 1 } )
WriteResult({ "nInserted" : 1 })
> db.foo.find().pretty()
{ "_id" : ObjectId("6274a6327ba4c1a412060b0f"), "x" : 1, "y" : 1 }
>
[root@localhost ~]# mongodump -d test -o /backup -u "myTester1" -p "Com.123456"
2022-05-06T12:40:30.518+0800 writing test.order to /backup/test/order.bson
2022-05-06T12:40:30.525+0800 done dumping test.order (1 document)
2022-05-06T12:40:30.531+0800 writing test.foo to /backup/test/foo.bson
2022-05-06T12:40:30.535+0800 done dumping test.foo (1 document)
2022-05-06T12:40:30.536+0800 writing test.books to /backup/test/books.bson
2022-05-06T12:40:30.538+0800 done dumping test.books (1 document)
2022-05-06T12:40:30.541+0800 writing test.tests to /backup/test/tests.bson
2022-05-06T12:40:30.545+0800 done dumping test.tests (0 documents)
[root@localhost ~]# cd /backup
[root@localhost backup]# ls
test
[root@localhost backup]# ll test
总用量 28
-rw-r--r--. 1 root root 37 5月 6 12:40 books.bson
-rw-r--r--. 1 root root 172 5月 6 12:40 books.metadata.json
-rw-r--r--. 1 root root 44 5月 6 12:40 foo.bson
-rw-r--r--. 1 root root 170 5月 6 12:40 foo.metadata.json
-rw-r--r--. 1 root root 281 5月 6 12:40 order.bson
-rw-r--r--. 1 root root 172 5月 6 12:40 order.metadata.json
-rw-r--r--. 1 root root 0 5月 6 12:40 tests.bson
-rw-r--r--. 1 root root 172 5月 6 12:40 tests.metadata.json
[root@localhost ~]# mongorestore -d test4 /backup/test/ -u "admin" -p "Com.123456" --authenticationDatabase admin
2022-05-06T12:43:41.304+0800 The --db and --collection flags are deprecated for this use-case; please use --nsInclude instead, i.e. with --nsInclude=${DATABASE}.${COLLECTION}
2022-05-06T12:43:41.304+0800 building a list of collections to restore from /backup/test dir
2022-05-06T12:43:41.304+0800 reading metadata for test4.foo from /backup/test/foo.metadata.json
2022-05-06T12:43:41.304+0800 reading metadata for test4.order from /backup/test/order.metadata.json
2022-05-06T12:43:41.304+0800 reading metadata for test4.tests from /backup/test/tests.metadata.json
2022-05-06T12:43:41.304+0800 reading metadata for test4.books from /backup/test/books.metadata.json
2022-05-06T12:43:41.337+0800 restoring test4.order from /backup/test/order.bson
2022-05-06T12:43:41.341+0800 restoring test4.books from /backup/test/books.bson
2022-05-06T12:43:41.347+0800 restoring test4.tests from /backup/test/tests.bson
2022-05-06T12:43:41.349+0800 finished restoring test4.order (1 document, 0 failures)
2022-05-06T12:43:41.352+0800 restoring test4.foo from /backup/test/foo.bson
2022-05-06T12:43:41.355+0800 finished restoring test4.books (1 document, 0 failures)
2022-05-06T12:43:41.358+0800 finished restoring test4.tests (0 documents, 0 failures)
2022-05-06T12:43:41.364+0800 finished restoring test4.foo (1 document, 0 failures)
2022-05-06T12:43:41.364+0800 no indexes to restore for collection test4.foo
2022-05-06T12:43:41.364+0800 no indexes to restore for collection test4.order
2022-05-06T12:43:41.364+0800 no indexes to restore for collection test4.books
2022-05-06T12:43:41.364+0800 no indexes to restore for collection test4.tests
2022-05-06T12:43:41.364+0800 3 document(s) restored successfully. 0 document(s) failed to restore.
[root@localhost test]# mongoexport -d test -c books -o /backup/test.books.json -u "admin" -p "Com.123456" --authenticationDatabase admin
2022-05-06T12:55:39.005+0800 connected to: mongodb://localhost/
2022-05-06T12:55:39.032+0800 exported 1 record
[root@localhost test]# cat /backup/test.books.json
{"_id":{"$oid":"62749a3ab3b46183247417aa"},"name":"java"}
[root@localhost ~]# mongoimport -d test -c test1 --file=/backup/test/test.order.json -u "admin" -p "Com.123456" --authenticationDatabase="admin"
2022-05-06T14:27:36.370+0800 connected to: mongodb://localhost/
2022-05-06T14:27:36.403+0800 1 document(s) imported successfully. 0 document(s) failed to import.
(s) restored successfully. 0 document(s) failed to restore.
#### 集合备份及恢复过程
###### 导出为.json文件
[root@localhost test]# mongoexport -d test -c books -o /backup/test.books.json -u “admin” -p “Com.123456” --authenticationDatabase admin
2022-05-06T12:55:39.005+0800 connected to: mongodb://localhost/
2022-05-06T12:55:39.032+0800 exported 1 record
[root@localhost test]# cat /backup/test.books.json
{“_id”:{“$oid”:“62749a3ab3b46183247417aa”},“name”:“java”}
###### 导入为.json文件
[root@localhost ~]# mongoimport -d test -c test1 --file=/backup/test/test.order.json -u “admin” -p “Com.123456” --authenticationDatabase=“admin”
2022-05-06T14:27:36.370+0800 connected to: mongodb://localhost/
2022-05-06T14:27:36.403+0800 1 document(s) imported successfully. 0 document(s) failed to import.