该知道的都知道 不知道的慢慢了解 MongoDB数据库操作详解

启动MongoDB

C:\Users\www61>mongo
MongoDB shell version v3.4.18-19-g6e6ee29489
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.18-19-g6e6ee29489
Server has startup warnings:
2020-12-01T16:46:05.311+0800 I CONTROL  [initandlisten]
2020-12-01T16:46:05.311+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-12-01T16:46:05.311+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-12-01T16:46:05.311+0800 I CONTROL  [initandlisten]
  1. 查看当前数据库的版本号:db.version()
> db.version()
3.4.18-19-g6e6ee29489
  1. 查看当前所在的数据库:db 默认是test数据库
> db
test
  1. 查看当前数据库连接的地址:db.getMongo()
> db.getMongo()
connection to 127.0.0.1:27017
  1. 查看所有数据库:show databases / show dbs
    注:数据库如果没有数据,不会显示
> show databases
admin  0.000GB
local  0.000GB
  1. 切换数据库:use 数据库名
    注:如果没有这个数据库,会先创建再切入 — 数据库的隐式创建
> use tt
switched to db tt
  1. 创建集合:db.createCollection(集合名)
> db.createCollection('class')
{ "ok" : 1 }
  1. 查看集合:show collections / show tables
> show tables
class
  1. 插入文档:
    db.集合名.insert({‘k’:‘v’})
    db.集合名.save({‘k’:‘v’})
    注1:如果想要插入多条数据,可以将多个对象放到一个数组中
    db.集合名.insert([{},{},{}])
    注2:如果插入数据的集合不存在,会先创建再插入 — 集合的隐式创建
> db.class.insert({'name':'zangpeng','age':19,'height':185})
WriteResult({ "nInserted" : 1 })
  1. 查询数据:db.集合名.find()
> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zangpeng", "age" : 19, "height" : 185 }

> db.class.insert([{'name':'wangbin','age':23,'height':177},{'name':'liyaohui','age':27,'height':175},{'name':'binjinhui','age':29,'height':169}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zangpeng", "age" : 19, "height" : 185 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 23, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 27, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }

10.查询当前数据库的状态:db.stats()

> db.stats()
{
        "db" : "tt",
        "collections" : 1,
        "views" : 0,
        "objects" : 4,
        "avgObjSize" : 70,
        "dataSize" : 280,
        "storageSize" : 16384,
        "numExtents" : 0,
        "indexes" : 1,
        "indexSize" : 16384,
        "ok" : 1
}

11.拷贝数据,将一个数据库中的数据拷贝到另一个数据库中
db.copyDatabase(‘数据库1’,‘数据库2’,‘地址’)

> db.copyDatabase('tt','cc','127.0.0.1')
{ "ok" : 1 }

> show databases
admin  0.000GB
cc     0.000GB
local  0.000GB
tt     0.000GB

> use cc
switched to db cc

> show tables
class

> db.teacher.insert([{'name':'wangbin','age':23,'height':177},{'name':'liyaohui','age':27,'height':175},{'name':'binjinhui','age':29,'height':169}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

12.删除集合:db.集合名.drop()

> db.class.drop()
true
> show tables
teacher

13.删除当前所在的数据库:db.dropDatabase()

> db.dropDatabase()
{ "dropped" : "cc", "ok" : 1 }

> show dbs
admin  0.000GB
local  0.000GB
tt     0.000GB

> use tt
switched to db tt

> db.teacher.insert([{'name':'wangbin','age':23,'height':177},{'name':'liyaohui','age':27,'height':175},{'name':'binjinhui','age':29,'height':169}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

> show tables
class
teacher

14.更新数据/修改数据:db.集合名.update(query,update[,upsert,multi])

query:条件 (小于: l t , 大 于 : lt,大于: lt,gt,等于: e q , 不 等 于 : eq,不等于: eqne,大于等于: g t e , 小 于 等 于 : gte,小于等于: gte,lte)

update:更新后的数据,新数据
$set: 设置值 $inc:增长值 $rename:重命名 $unset:删除

upsert:可选参数,是一个布尔值。作用:如果不存在update记录,是否插入更新的数据?
true:代表插入,false:代表不插入 默认是false

multi:可选参数,是一个布尔值。作用:是否将查询出来的所有符合条件的数据,全部更新?
true:全部更新 false:更新第一条 默认是false

> db.class.update({'name':'zangpeng'},{'name':'zhaodapeng'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zhaodapeng" }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 23, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 27, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }


> db.class.update({'age':27},{'$set':{'age':18}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zhaodapeng" }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 23, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 18, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }

> db.class.update({'age':{'$lte':27}},{'$set':{'age':18}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zhaodapeng" }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 18, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 18, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }

> db.class.update({'name':'wangbin'},{'$set':{'age':18}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zhaodapeng" }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 18, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 18, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }
> db.class.update({'name':'wangbin'},{'$set':{'age':22}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zhaodapeng" }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 22, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 18, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }

> db.class.update({'age':{'$lte':22}},{'$set':{'age':20}},{'multi':true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.class.find()
{ "_id" : ObjectId("5fc6f80fa376f401b4186ae0"), "name" : "zhaodapeng" }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 20, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }
>

15.删除文档:remove(query[,justOne])
query: 必选项
justOne:可选参数,代表是否只删除一条数据,是一个布尔值。默认false
db.集合名.remove({}) 删除全部文档
db.集合名.remove(query) 根据条件删除,删除全部符合条件的数据
db.集合名.remove(query,true/false) 是否只删除一条数据

> db.class.remove({'name':'zhaodapeng'})
WriteResult({ "nRemoved" : 1 })
> db.class.find()
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 20, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }
>

16.查询文档:find([query,是否显示此字段])

db.集合名.find() 查询所有文档
db.集合名.find(query) 查询所有符合条件的文档
db.集合名.find(query,{k:1(显示)/0(不显示)})
注:find()方法查询时,查询出来的数据是一行显示的,可以使用pretty()将数据格式化输出

db.集合名.findOne([query,是否显示此字段]) 只查询一条数据,返回的数据格式是格式化之后的形式,所以,此方法不能使用pretty()

> db.class.find({'name':'wangbin'})
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 20, "height" : 177 }
> db.class.find({'name':'wangbin'},{'age':1})
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "age" : 20 }
>
> db.class.find().pretty()
{
        "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"),
        "name" : "wangbin",
        "age" : 20,
        "height" : 177
}
{
        "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"),
        "name" : "liyaohui",
        "age" : 20,
        "height" : 175
}
{
        "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"),
        "name" : "binjinhui",
        "age" : 29,
        "height" : 169
}

17.查询某一列去重后的数据
MySQL:select distinct 字段 from 表
MongoDB:db.集合名.distinct(k)

操作之前先增加两行重复的数据

> db.class.insert([{'name':'yy','age':20,'height':180},{'name':'yy','age':11,'height':140}])
> db.class.find()
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 20, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }
{ "_id" : ObjectId("5fc783cc7a73629437d11bcd"), "name" : "yy", "age" : 20, "height" : 180 }
{ "_id" : ObjectId("5fc783cc7a73629437d11bce"), "name" : "yy", "age" : 11, "height" : 140 }
> 
> > db.class.distinct('name')
[ "wangbin", "liyaohui", "binjinhui", "yy" ]

18.MongoDB中AND条件的使用:多个条件以逗号分隔
MySQL:select * from xxx where xxx=xxx and xxx=xxx
MongoDB:db.集合名.find({‘k1’:‘v1’,‘k2’:v2,……})

> db.class.find({'name':'yy','height':140})
{ "_id" : ObjectId("5fc783cc7a73629437d11bce"), "name" : "yy", "age" : 11, "height" : 140 }

19.MongoDB中OR条件的使用:$or
MySQL:select * from xxx where xxx=xxx or xxx=xxx
MongoDB:db.集合名.find({’$or’:[{k1:v1},{k2:v2},……]})

> db.class.find({'$or':[{'name':'liyaohui'},{'height':140}]})
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc783cc7a73629437d11bce"), "name" : "yy", "age" : 11, "height" : 140 }

20.MongoDB中的限制查询:
MySQL:select * from xxx limit 2
MongoDB:db.集合名.find().limit(n) 查询前n条数据

> db.class.find().limit(2)
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 20, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }

21.MongoDB中的skip()
MySQL:select * from xxx limit 2,3
MongoDB:db.集合名.find().skip(n) 跳过前n条数据,从n+1条开始查询

> db.class.find().skip(1)
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }
{ "_id" : ObjectId("5fc783cc7a73629437d11bcd"), "name" : "yy", "age" : 20, "height" : 180 }
{ "_id" : ObjectId("5fc783cc7a73629437d11bce"), "name" : "yy", "age" : 11, "height" : 140 }

22.MongoDB中的分页:
db.集合名.find().skip(n).limit(m) 跳过前n条数据,从n+1条开始查询,查询m条数据

> db.class.find().skip(1).limit(2)
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }

23.MongoDB中的模糊查询:
MySQL:select * from 表 where name like %xxx%
MongoDB:db.集合名.find({‘k’:/xxxx/})

> db.class.find({'name':/hui/})
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }

24.MongoDB中的排序:sort()
db.集合名.find().sort({‘k’:1(正序,从小到大)/-1(倒叙,从大到小)})

> db.class.find().sort({'age':-1})
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae3"), "name" : "binjinhui", "age" : 29, "height" : 169 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae1"), "name" : "wangbin", "age" : 20, "height" : 177 }
{ "_id" : ObjectId("5fc6f8d2a376f401b4186ae2"), "name" : "liyaohui", "age" : 20, "height" : 175 }
{ "_id" : ObjectId("5fc783cc7a73629437d11bcd"), "name" : "yy", "age" : 20, "height" : 180 }
{ "_id" : ObjectId("5fc783cc7a73629437d11bce"), "name" : "yy", "age" : 11, "height" : 140 }

25.MongoDB中的统计:
MySQL:select count(*) from xxx
MongoDB:db.集合名.find().count()

> db.class.find().count()
5

26.MongoDB中的游标:
插入1000条数据:
for(var i=1;i<=1000;i++){
db.集合名.insert({k:v,……})
}

> for(var i=1;1<=1000;i++){
... db.class.insert({'name':i,'age':i,'height':180})
... }

1 什么是游标?
MongoDB中的游标和MySQL中的游标非常相似,可以通过对游标进行一系列的设置来控制游标查询数据,游标并不是查询的结果,而是查询的一个返回资源或者接口,通过这个接口可以逐条读取数据,和Python中的生成器类似,游标会消耗内存资源,所以,在游标使用之后,应该尽快释放掉,在MongoDB中,如果游标被定义之后,没有使用变量接收,那么就是一个查询结果,默认自动迭代20次,可以使用
DBQuery.shellBatchSize=n n是一个数字,即一次显示的数据量

2.游标的使用
2.1 声明游标:var cursor=db.集合名.find()
2.2 next():可以移动游标,取出文档
2.3 print(cursor.next()) 返回一个[Object Bson],是Json的二进制类型
2.4 hasNext() 查看游标是否能够继续移动,返回值是布尔值,true代表能够继续移动,false代表不能继续移动
2.5 while(cursor.hasNext()){
printjson(cursor.next())
}

2.6 使用forEach()方法进行迭代 cursor.forEach(函数)
var cursor=db.集合名.find()
var getContent=function(obj){
printjson(obj.content)
}
cursor.forEach(getContent)

2.7 游标的声明周期:
游标迭代到最后一条数据时,自动关闭

你可能感兴趣的:(数据库,mongodb)