生于理想

导航

MongoDB增删改查

向数据库中导入数据

mongoimport -d 数据库名称 -c 集合名称 --file 要导入的文件

mongoimport -d playground -c users --file ./user.json

 

查询

// 查询用户集合中的所有文档
// User.find().then(result => console.log(result));
// 通过_id字段查找文档
// User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// findOne方法返回一条文档 默认返回当前集合中的第一条文档
// User.findOne({name: '李四'}).then(result => console.log(result))
// 查询用户集合中年龄字段大于20并且小于40的文档
// User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result))
// 查询用户集合中hobbies字段值包含足球的文档
// User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))
// 选择要查询的字段
// User.find().select('name email -_id').then(result => console.log(result))
// 根据年龄字段进行升序排列
// User.find().sort('age').then(result => console.log(result))
// 根据年龄字段进行降序排列
// User.find().sort('-age').then(result => console.log(result))
// 查询文档跳过前两条结果 限制显示3条结果
User.find().skip(2).limit(3).then(result => console.log(result))

 

删除

// 查找到一条文档并且删除
// 返回删除的文档
// 如何查询条件匹配了多个文档 那么将会删除第一个匹配的文档
// User.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// 删除多条文档
User.deleteMany({}).then(result => console.log(result))

 

更新

//更新集合中的文档(更新1个)
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))

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

// 根据id更新
Course.findByIdAndUpdate(id, {
    $set: {
        author: 'mosh',
        isPublished: false
    }
}, err => {})

posted on 2022-09-20 18:20  生于理想  阅读(32)  评论(0)    收藏  举报