数据库操作
查看当前操作库
db
查看所有数据库
show dbs
数据库为空则不显示在列表中
local和demo数据库 显示为0.000GB并不为空
local用于维护MongoDB的运行
切换数据库
use test
如果有test数据库则切换到该数据库 如果没有则创建
集合内增删改查:
1.新增
1.1 新增单个
db.getCollection(‘excel1’).insertOne({name:‘李四’,sex:‘女’,tel:‘13728868878’});
1.2新增多个
db.getCollection('excel1').insertMany([
{name:'王老五',sex:'男',tel:'13728860799'},
{name:'胡巴',sex:'男',tel:'13728860791'}
])
2.查询
2.1.1 简单查询
db.db.getCollection('集合名’).find(查询条件[,过滤])
db.getCollection('excel1').find({});
默认查询该集合所有. findOne默认只查询一个
2.1.2(投影)查询过滤
db.getCollection('excel1').find({'sex':'男'},{name:1,sex:1});
- find中传入的第一个形参为筛选条件,第二个形参用于控制输出,例如name和sex为真
则只显示name和sex,此处的_id,只要你不做特别强调,它是一直在的,除非你传入_id:0;
db.getCollection('excel1').find({'sex':'男'},{name:1,sex:1,_id:0})
- 我们把第二形参数当成两部分看,_id为一部分,另一部分(name,sex)要么全为真,要么全为假,不能混着用
db.getCollection('excel1').find({'sex':'男'},{name:1,sex:1,tel:0,_id:0})
2.2复杂查询
当我们想查询学生性别为男并且年龄小 于18的,如何去查询
db.getCollection(‘excel1’).find({sex:’男’,age:{$lt:18}})
至于为什么是 age:{$lt:18}}),而不是age<18,对不起,写起来就是这么恶心,常用操作符如下:
< | $lt |
<= | $lte |
> | $gt |
>= | $gte |
!== | $ne |
或 | $in 或者 $or |
非 | $on |
find也支持函数查询….
3.更新
db.getCollection(‘集合名’).update({查询条件},{需要更新的内容},{配置})
更新单个对象
db.getCollection(‘excel1’).update({name:‘李四’},{$set:{sex:‘男’}})
更新多个对象
db.getCollection(‘excel1’).update({sex:‘女’},{$set:{name:‘批量’}},{multi:true})
你也可以使用updateOne和updateMany方法 可省略设置multi
4.删除
db.getCollection(‘集合名’).remove(查询条件)
db.getCollection(‘excel1’).remove({sex:‘女’})