MongoDB数据库使用API

启动MongoDB

net start mongoDB

net stop mongoDB

连接数据库

mongoose.connetc('mongodb://localhost/playground').then( () => console.log('数据库连接成功')).catch( err => {console.log('数据库连接失败!')})

在MongoDB中如果使用的数据库不存在,就会被创建!

创建集合

  • 对集合设定规则

  • 创建集合

    // 设定集合规则
    const courseSchema = new mongoose.Schema({
        name: String,
        author: String,
        isPubulished: Boolean
    })
    // 创建集合并应用规则
    const Course = mongoose.model('Course', courseSchema)

插入数据

  • 创建集合实例

  • 调用实例对象下的save方法将数据保存到数据库中

    // 创建文档实例
    const course = new Course({
        name: 'Node js ',
        tags: ['node', 'test'],
        isPublished: true
    })
    // 保存文档实例
    course.save()
  • create方法

    Course.create({
        name: 'kangkang',
        age: 19,
        isPublish: true
    }, (err,doc) => {
        if(err) {
            console.log(err) 
            return
        }
        console.log(doc)
    })
    
    
    Course.create({
        name: 'kangkang',
        age: 19,
        isPublish: true
    }).then(doc => {}).catch(err => {console.log(err)})

查询数据

如何将数据导入数据库中

// -d 代表数据库  -c 导入哪个集合中 -file 要导入的文件
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件
// 返回文档的集合
Course.find().then(result => console.log(result))

精确查找

  • find

  • findOne 没有条件返回当前集合的第一个

模糊查找

// $gt 大于 $lt小于
City.find({age: {$gt: 20, $lt: 50}}).then(result => {console.log(result)})
// 包含
City.find({citys: {$in:['足球']}}).then(result => {console.log(result)})
// 选择需要查询的字段 -_id表示去除_id字段
City.find().select('name age -_id').then(result => {console.log(result)})
// 将数据按照某个字段进行排序(升序)
City.find().sort('name').then(result => {console.log(result)})
// 将数据按照某个字段进行排序(降序)
City.find().sort('-name').then(result => {console.log(result)})
// skip跳过多少条,limt限制多少条数 (分页)
City.find().skip(2).limt(2).then(result =>{console.log(result)})

删除文档

// 删除单个,查找第一个并删除
City.findOneAndDelete({}).then(result =>{console.log(result)})
// 删除多个
City.deleteMany({}).then(result =>{
    // 一个对象{n:2, Ok: 1} ok-1删除成功,n是删除的个数
    console.log(result)
})

更新文档

// 更新单个
City.updateOne({查询条件}, {要修改的值}).then(result => {
    console.log(result)
})
// 更新多个
City.updateMany({查询条件}, {要更改的值}).then(result => {
    console.log(result)
})

猜你喜欢

转载自www.cnblogs.com/daixixi/p/12208663.html
今日推荐