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 => {})
分类:
Node
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现