MongoDB简单的使用

本文详细介绍了MongoDB的架构特点,包括其与传统关系数据库的区别,以及如何在Windows环境下搭建MongoDB数据库。深入探讨了MongoDB的基本命令,涵盖数据库、集合、文档的操作,以及数据的增删改查。同时,提供了Node.js中MongoDB的DAO封装示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MongoDB简介

传统的关系数据库(如mysql)一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。
MongoDB的优点:易扩展、高性能、灵活的数据模型
MongoDB的缺点:数据重复存储,占用空间大

使用数据库

1.创建一个新的文件夹,这个文件夹就是数据库
2.数据库开机 mongod --dbpath 文件夹路径
例如: mongod --dbpath C:\Users\Administrator\Desktop\mongoData

  • 最后出现waiting for connctions prot : 27017就表示数据库已经启动成功了
    注意:
    电脑的权限;
    开机以后当前的cmd命令窗口就不要动了,因为数据库也是一种服务,关闭了就停止了。直接最小化就不用去管它了

3.使用数据库
打开一个新的cmd命令窗口,连接数据库mongo命令,连接数据库,连接成功以后就可以直接去写mongodb的语法对数据库进行操作

mongoDB的基础命令

数据库常用命令
1、show dbs 列出所有数据库

  • adminlocal 系统数据库

2、use 数据库名 创建并使用数据库
3、db/db.getName() 查看当前所在数据库
4、db.dropDatabase() 删除当前使用数据库(慎用),不会给你提示
5、db.stats() 显示当前db状态
6、db.version() 当前db版本
7、db.getMongo() 查看当前数据库的链接机器地址

操作集合的命令
1、创建集合

  • 不手动创建集合:向不存在的集合中第⼀次加⼊数据时, 集合会被创建出来
  • 手动创建集合:db.createCollection(name)

2、得到当前db的所有聚集集合:db.getCollection("account");
得到指定名称的聚集集合:db.getCollectionNames();
3、删除集合:db.集合名称.drop()
4、列出当前所在数据库的所有集合:show collections

插入数据

单条数据: db.student.insert({"name":"jack","age":18})
多条数据 :db.student.insertMany([{"name":"jack","age":19},{"name":"jack","age":20}])
导入数据: 一定是重新打开一个新的cmd命令窗口
mongoimport --db 数据库名称 --collection 集合名称 [--drop](是否清空当前集合) --file 文件路径

删除数据

单条数据:db.集合名称.remove(<query>,{justOne: <boolean>})

  • 参数query:可选,删除的⽂档的条件
  • 参数justOne:可选, 如果设为true或1, 则只删除⼀条, 默认false, 表示删除多条
  • 例:db.student.remove({"name":"jack"}) db.student.remove({"name":"jack"},1)
    多条数据:db.student.remove()
更新数据

语法: db.集合名称.update(<query> ,<update>,{multi: <boolean>})

  • 参数query:查询条件
  • 参数update:更新操作符
  • 参数multi:可选, 默认是false,表示只更新找到的第⼀条记录, 值为true表示把满⾜条件的⽂档全部更新
  • 例:db.student.update({"name":"张三"},{"name":"jack"}) 更新一条,没有更新的字段会丢弃
  • db.student.update({"name":"张三"},{$set:{"name":"jack"}}) 更新一条
  • db.stu.update({},{$set:{gender:0}},{multi:true}) 更新全部
查询数据

1、查询所有记录 db.userInfo.find();
相当于:select* from userInfo;
2、查询去掉后的当前聚集集合中的某列的重复数据 db.userInfo.distinct("name");
会过滤掉name中的相同数据
相当于:select distict name from userInfo;
3、条件查询

1.查询age = 22的记录
 db.userInfo.find({"age": 22});
 相当于: select * from userInfo where age = 22;
2.查询age > 22的记录
 db.userInfo.find({age: {$gt: 22}});
 相当于:select * from userInfo where age >22;
3.查询age < 22的记录
 db.userInfo.find({age: {$lt: 22}});
 相当于:select * from userInfo where age <22;
4.查询age >= 25的记录
 db.userInfo.find({age: {$gte: 25}});
 相当于:select * from userInfo where age >= 25;
5.查询age <= 25的记录
 db.userInfo.find({age: {$lte: 25}});
6.查询age >= 23 并且 age <= 26
 db.userInfo.find({age: {$gte: 23, $lte: 26}});
7.查询name中包含 mongo的数据
 db.userInfo.find({name: /mongo/});
 //相当于%%
 select * from userInfo where name like ‘%mongo%’;
8. 查询指定列name、age数据
 db.userInfo.find({}, {name: 1, age: 1});
 相当于:select name, age from userInfo;
   name也可以用true或false,当用ture的情况下河name:1效果一样,如果用false就是排除name,显示name以外的列信息。
9. 查询指定列name、age数据, age > 25
 db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
 相当于:select name, age from userInfo where age >25;
10.按照年龄排序
 升序:db.userInfo.find().sort({age: 1});
 降序:db.userInfo.find().sort({age: -1});
10. 查询前5条数据
 db.userInfo.find().limit(5);
 相当于:selecttop 5 * from userInfo;
11. 查询10条以后的数据
 db.userInfo.find().skip(10);
12. 查询在5-10之间的数据 用于分页,limit是pageSize,skip是第几页*pageSize
 db.userInfo.find().limit(10).skip(5);
13. or与 查询
 db.userInfo.find({$or: [{age: 22}, {age: 25}]});
 相当于:select * from userInfo where age = 22 or age = 25;
14.查询某个结果集的记录条数
 db.userInfo.find({age: {$gte: 25}}).count();
 相当于:select count(*) from userInfo where age >= 20;
15. 按照某列进行排序
 db.userInfo.find({sex: {$exists: true}}).count();
 相当于:select count(sex) from userInfo;
nodejs中封装DAO
// 连接数据库
const MongoClient = require("mongodb").MongoClient;
//访问数据库
function _connectDB(callback){
    // 数据库地址
    const dburl = "mongodb://127.0.0.1:27017/school";
    MongoClient.connect(dburl,(err,db)=>{
        if(err){
            callback(err,null);
            return;
        }
        callback(err,db);
    })
}
// 添加数据
exports.insertOne = function(collectionName,json,callback){
    _connectDB(function(err,db){
        db.collection(collectionName).insertOne(json,(err,result)=>{
            callback(err,result);
            db.close();
        })
    })
}
// 删除数据
exports.deleteOne = function(collectionName,json,callback){
    _connectDB(function(err,db){
        db.collection(collectionName).deleteOne(json,(err,result)=>{
            callback(err,result);
            db.close();
        })
    })
}
// 修改数据
exports.updateOne = function(collectionName,json1,json2,callback){
    _connectDB(function(err,db){
        db.collection(collectionName).updateOne(json1,json2,(err,result)=>{
            callback(err,result);
            db.close();
        })
    })
}
// 查询数据
exports.find = function(collectionName,json,C,D){
    // 返回结果
    var result = [];
    if(arguments.length == 3){//不分页
        var callback = C;
        var skipnum = 0;
        var limitnum = 0;
    }else if(arguments.length == 4){//分页
        var callback = D;
        var args = C;
        // 省略的条数
        var skipnum = args.page || 0;
        // 查询几条数据
        var limitnum = args.pagenum || 0;
    }else{
        throw new Error("find函数只能传三个或四个参数");
    }
    _connectDB(function(err,db){
        const cursor = db.collection(collectionName).find(json).limit(limitnum).skip(skipnum * limitnum);
        cursor.each((err,document)=>{
            if(err){
                callback(err,null);
                db.close();
                return;
            }
            if(document != null){
                result.push(document);
            }else{
                callback(null,result);
                db.close();
            }
        })
    })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值