当前位置 博文首页 > 向往的那片海洋:MongoDB 增删查改(一)

    向往的那片海洋:MongoDB 增删查改(一)

    作者:[db:作者] 时间:2021-08-20 21:45

    查询文档

    • 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
    下一篇:没有了