MongoDB基本使用

知识导航:

  • 1 MongoDB简单介绍
  • 2 创建集合
  • 3 插入数据
  • 4 删除文档
  • 5 修改数据
  • 6 查询数据
  • 7 集合关联

1 MongoDB简单介绍

mongo数据库与mysql有很大的不同,它们没有表的概念,它的数据是以json数据存储的。它的基本数据结构如下:

database数据库,mongoDB数据库软件中可以建立多个数据库
collection集合,一组数据的集合,可以理解为mysql中的表
document文档,类似mysql中表的一条数据
field字段,mysql表中一条数据中的单一属性

值得注意:
在node中使用mongodb要借助于第三方包来帮助
下载命令:npm install mongoose
开启mongodb数据库服务命令net start mongoDB

连接基本语法:
connect()方法返回的是promise对象,故我们可以用它的then和catch方法

const mongoose = require('mongoose');
//text是数据库的名字,若mongodb中没有会自动帮我们创建
mongoose.connect('mongodb://localhost/text', { useUnifiedTopology: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));

2 创建集合

集合的创建分为两步

  1. 创建集合规则
  2. 创建集合
// 设置集合规则
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    address: String
});
//创建集合
const Student = mongoose.model("Student", studentSchema);

3 插入数据

方法一:
紧接上面已经创建了Student 的集合

// 向集合内插入数据
const student = new Student({
    name: "宫小白",
    age: 18,
    address: "中国河北"
});
// 保存
student.save();

方法二:

Student.create({ name: "王五", age: 100, address: "中国北京" }).then(() => {
    console.log("插入成功");
})

查看结果:
在这里插入图片描述

4 删除文档

来看栗子吧:

4.1 删除匹配的一个

如把上面的王五删掉(ps我把代码写全一点)

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/text', { useUnifiedTopology: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));
// 设置集合规则
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    address: String
});
//创建集合
const Student = mongoose.model("Student", studentSchema);

//删除匹配的一个
Student.findOneAndDelete({ name: '王五' }).then(res => {
    console.log(res);

});

先看一下执行结果:(其返回了被删除的数据)
在这里插入图片描述
再来看下数据库中内容:
在这里插入图片描述

4.2 删除匹配的多个

没有数据库里没有数据了直接放代码吧

//删除匹配的多个
Student.deleteMany({ age: 100 }).then(res => {
    console.log(res);
});

5 修改数据

5.1 更新一个

把宫小白的年龄更新为20

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/text', { useUnifiedTopology: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));
// 设置集合规则
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    address: String
});
//创建集合
const Student = mongoose.model("Student", studentSchema);
Student.updateOne({ name: "宫小白" }, { age: 20}).then(res => {
    console.log(res);
});

在这里插入图片描述

5.2 更新多个

Student.updateMany({查询条件}, {要更改的值}).then(res=> console.log(res))

6 查询数据

6.1 查询该集合的所有文档

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/text', { useUnifiedTopology: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));
// 设置集合规则
const studentSchema = new mongoose.Schema({
    name: String,
    age: Number,
    address: String
});
//创建集合
const Student = mongoose.model("Student", studentSchema);
// 查询该集合下的所有
Student.find().then(res => {
    console.log(res);

});

6.2 通过某一条件查

// 通过姓名查找
Student.find({ name: "张三" }).then(res => {
    console.log(res);
});

6.3 返回匹配的第一条数据

// 返回当前集合的第一条
Student.findOne().then(res => {
    console.log(res);

});

6.4 条件查找

// 条件查找
//年龄字段大于50并且小于110
Student.find({ age: { $gt: 50, $lt: 110 } }).then(res => {
    console.log(res);
});

6.5 只查询相关字段

// 只查询相关字段
Student.find().select('name age').then(result => console.log(result))

看返回结果:
在这里插入图片描述

6.6 排序查找

// 排序
// 按年龄升序
Student.find().sort('age').then(result => console.log(result));
//按年龄降序
Student.find().sort("-age").then(result => console.log(result));

6.7 自定义跳过,限制条数

// 查询文档跳过第一条结果 限制显示3条结果
Student.find().skip(1).limit(3).then(res => {
    console.log(res);
});

7 集合关联

场景:有商品集合和商品制作者集合
商品集合中有字段保存的是它的制作者。怎么给两个集合创建联系呢?
看下面栗子:
先准备一个制造者集合:(ps:在创建集合规则时,可以设置当前字段的验证规则。
规则属性如下:

  • required: true - 必传字段
  • minlength: - 2字符串最小长度
  • maxlength: 20 - 字符串最大长度
  • min: 2 - 数值最小为20
  • max: 100 - 数值最大为100
  • enum: [“篮球”, “足球”, “乒乓球”] - 只能在这个范围选
  • trim: true - 去除字符串两边的空格
  • validate: - 自定义验证器
  • 使用参看下面这个栗子
    )
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/text', { useUnifiedTopology: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));
// 设置集合规则
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        //必填
        required: [true, '请传入文章标题'],
        minlength: [3, "最小长度不少于3"],
        maxlength: [5, "最大长度不超过5"],
        trim: true

    },
    age: {
        type: Number,
        min: 10,
        max: 120
    },
    address: {
        type: String,
        validate: {
            validator: v => {
                return v && v.length > 2
            },
            message: "不符合规则"
        }
    },
    hobbies: {
        type: String,
        enum: {
            values: ["篮球", "足球", "乒乓球"],
            message: '爱好在一定的范围'
        }
    }
});
//创建集合
const User = mongoose.model("User", userSchema);
User.create({ name: "宫小白", age: 19, address: "中国河北", hobbies: "篮球" });

商品集合:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/text', { useUnifiedTopology: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        //必填
        required: [true, '请传入文章标题'],
        minlength: [3, "最小长度不少于3"],
        maxlength: [5, "最大长度不超过5"],
        trim: true

    },
    age: {
        type: Number,
        min: 10,
        max: 120
    },
    address: {
        type: String,
        validate: {
            validator: v => {
                return v && v.length > 2
            },
            message: "不符合规则"
        }
    },
    hobbies: {
        type: String,
        enum: {
            values: ["篮球", "足球", "乒乓球"],
            message: '爱好在一定的范围'
        }
    }
});
//创建集合
const User = mongoose.model("User", userSchema);
// 设置集合规则
const productSchema = new mongoose.Schema({
    name: String,
    producter: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    data: Date
});
//创建集合
const Product = mongoose.model("Product", productSchema);
Product.create({ name: "八宝粥", producter: "5e4e6fd9a54db04618d38984" });
Product.find().populate('producter').then(result => console.log(result))

看它的制造者已经被关联到
在这里插入图片描述

  • 10
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值