**MongoDB基本语法——数据库操作**
db:查看当前指向的数据库
show dbs:查看当前所有的数据库
use 切换到当前数据库
db.dropDatabase():删除当前指向的数据库
**MongoDB基本语法——集合操作*
show collections:查看当前数据库所有集合
db.createCollection( [ options]):创建一个集合
db.<集合名称>.drop():删除指定的集合
############增删改#############
增加
db.hero.insert({键值对})
db.hero.insert({"_id" : 1})
修改
db.hero.update({name:"swk"},{$set:{name:"bajie"}})
db.hero.update({tiaojian},{$set:{ }},{multi:true})
multi:true 表示修改所有 // 默认false 表示修改符合条件第一条
删除
db.hero.remove({ }) #删除所有
db.hero.remove({ },{justOne:true}) #只删除一条
保存
db.hero.save({ })
save 相当于update insert
##############查询#############
1.基本查询
db.hero.find()
findOne([{文档条件}]):查询第一个
db.hero.find()pretty()
pretty():将查询结果格式化展示
2.比较运算符(关系运算符)$lt $lte $gt $gte
$lt :little ~小于 < #less than
$lte :little or equals ~小于等于 <=
$gt :granter ~大于 >
$gte :granter or equals ~大于等于 >=
db.hero.find({age : {$gt : 18}})
db.hero.find({age : {$lte : 16}})
3.逻辑运算符 $or
db.hero.find({$or : [{},{},{},{}] })
db.hero.find({$or : [{name:"sunquan"},{age:{$lte:16}}] })
db.hero.find({$or : [{age:{$gt:20}},{age:{$lt:40}}] }) #年龄大于20小于40
db.hero.find({$or : [{age:{$gt:20}},{age:{$lt:40}}] },sex:"nan") #并且是男的
4.范围运算符
$in:判断指定条件是否包含在某个范围内
db.hero.find( {age : {$in : [20,30,40]} } )
$nin:判断指定条件是否不包含在某个范围内
5.正则条件
#从一个字符串中匹配一个结果
/reg/:普通正则表达式
db.hero.find({ http : /^www/ }) #表示匹配一条http以www开头的数据
db.hero.find({ name : /^zhang/}) #表示name以zhang开头
db.hero.find({ http : /com$/ }) #表示http以com结尾
$regex:指定正则表达式db.hero.find({ name : {$regex : "^lee"} })
db.hero.find({ name : {$regex : "."} }) # .任意匹配
6.自定义条件
$where:通过函数自定义条件[JS函数]
指定函数中,返回boolean类型的值
this表示每个要查询的文档
db.hero.find({where : function() {return this.name=="songjia"}})
db.hero.find({where : function() {return this.age > 30}})
7.数据查询——限制查询条数
db.hero.find(2) #查询前两条
db.hero.find().skip(2) #跳过两条
db.hero.find().skip(0).limit(10) #从头查询十条内容
db.hero.find().skip(10).limit(10) #跳过十条再查询十条
8.数据查询——统计
db.hero.count() #统计总共条数
db.hero.count({条件}) #统计符合条件的数据条数
db.hero.find().count()
db.hero.find({条件}).count() #同上述一样
9.数据查询——投影:查询制定的域
find({},{投影字段:1/0}) #1显示 0不显示
db.hero.find({},{name:1})
得到结果
{ "_id" : 24, "name" : "linchong"}
{ "_id" : 25, "name" : "luzhishen"}
{ "_id" : 26, "name" : "huarong"}db.hero.find({},{name:1 ,_id:0})
得到结果
{"name" : "linchong"}
{"name" : "luzhishen"}
{"name" : "huarong"}
10.数据查询——排序(1/-1)
db.hero.find().sort({}) #默认升序
db.hero.find().sort({条件})
db.hero.find().sort({name:1},{age:1})
db.hero.find().sort({name:-1}) #降序
11.数据查询——去重distinct
db.hero.distinct("去重域名称",{条件}}
db.hero.distinct("age",{}}
得到结果
[21,22,23,24,25]