当前位置 博文首页 > 向往的那片海洋:MongoDB 增删查改(一)
find()
方法:返回一个数组,不传参数返回所有文档findOne()
方法:查找会返回一个对象,返回一条文档,默认返回当前集合中的第一条文档Course.find().then(result => console.log(result));
Course.findOne().then(result => console.log(result));
$gt
)、小于($lt
):// 查询用户集合中年龄字段大于 20 并且小于 50 的文档
// $gt 大于 $lt 小于
Course.find({age:{$gt:20,$lt:50}}).then(result => console.log(result))
$in
)// 查询字段为 code 的文档
Course.find({hobbies:{$in:['code']}}).then(result => console.log(result))
select()
方法// select('字段名字')
// 不想查询的字段: -字段名
Course.find().select('name email').then(result => console.log(result))
sort()
方法sort()
方法排序,默认升序
sort('字段名')
:升序sort('-字段名')
:降序Course.find().sort('age').then(result => console.log(result))
Course.find().sort('-age').then(result => console.log(result))
skip
跳过多少条数据 limit
限制查询数// skip(2).limit(2) 跳过两条数据,只查询两条数据
Course.find().skip(2).limit(2).then(result => console.log(result))
findOneAndDelect()
方法Course.findOneAndDelete({}).then(result => console.log(result))
deleteMany()
方法// 返回值为一个对象 {n:2 ok:1} // 共删除两个(2),删除成功(1)
Course.deleteMany({}).then(result => console.log(result))
// 更新单个
// {author:'change'} 条件 {author:'启嘉'} 修改后的值
Course.updateOne({author:'change'},{author:'启嘉'}).then(result => console.log(result))
// {} 不传参,默认所有
Course.updateMany({},{name:'web'}).then(result => console.log(result))
cs