一、数据库操作。
show dbs(show databases)
use database //use or create
db.dropDatabase()
db.stats() //database information
二、集合操作。
(1)创建集合(指定创建)
db.createCollection(“collection_name1”) or
db.createCollection("cn",{"capped":true,"size":1000,"max":100})
(2)创建集合(默认创建):向不存在的集合里插入文档
db.collection_name2.insert({“name”:”zs”,”age”:20})
(3)查看集合
show tables 或 show collections
db.collections.stats()
(4)删除集合
db.collections.drop()
(5) 获取所有集合
db.getCollectionNames()
三、文档操作。
1.插入操作:
db.collections.insert({“name”:”zhangsan”,”age”:20})
db.collections.insertOne({“name”:”wangwu”,”age”:18})
db.collections.insert([{},{},{}])
db.collections.insertMany([{},{},{}])
v=({“name”:”xiaobai”,”age”:”5”})
db.collections.insert(v)
2.查询操作:
(1)无条件查询集合中文档
db.collections.find()
(2)带条件查询集合中文档
db.collections.find({})
db.collections.find({“name”:”zhangsan”})
db.collections.find({“age”:30})
(3)查询一个文档
db.collections.findOne()
db.collections.findOne({})
db.collections.findOne({“age”:20})
(4)投影查询
db.collections.find({},{“name”:1}) //“_id”始终会被获取
db.collections.find({},{“name”:1,”_id”:0})//”_id”不会被获取
(5)复合查询(或者,并且)
db.collections.find({“name”:”zhangsan”,“age”:25})
db.collections.find({“$or”:[{“name”:”zhangsan”},{“age”:25}]})
db.collections.find({“$or”:[{“name”:”zhangsan”},{“age”:25}],”sex”:1})
(6)type查询
db.collections.find({“name”:{“$type”:”string”}})
(7)正则匹配
db.collections.find({“name”:/^z/}) //以z开头
或db.collections.find({“name”:{$regex:/^z/}})
db.collections.find({“name”:/y$/}) //以y结尾
db.collections.find({“name”:/^z.*y$/}) //一个点代表一个字符
db.collections.find({“name”:/z/}) //包含z
db.collections.find({“name”:/z/i}) //忽略大小写
或db.collections.find({“name”:{$regex:/^z/,$options:’i’}})
db.collections.find({“name”:{“$in”:[/^l/,/^z/]}}) $nin
db.collections.find({“name”:{$not:/^z/}})
(8)分页查询
使用函数limit()和skip()来实现分页查询
db.collections.find().limit().skip() //跳过多少行查询多少行
(9)查询排序
db.collectins.find().sort({“age”:-1,”name”:1})
四、更新操作。
1.覆盖更新:
Db.collections.update({“name”:”zhang”},{“name”:”li”,”age”:15})
//只会更新一条数据,按照集合的自然顺序
2.表达式更新:
Db.collections.update({“name”:”zhang”},{“$set”:{“name”:”li”}})
//set会判断set的字段存在则修改,不存在则添加
五、删除操作。
db.collections.remove({“age”:30})
db.collections.deleteOne({“age”:20})
db.collections.deleteMany({“age”:20})