MongoDB database operations and operation commands

Table of contents

1. Basic concepts

2. Install mongod

 3. Command interaction database

(1) Database commands

(2) Collection command

(3) Document command

 4. Mongoose

(1) Add a piece of data

(2) Insert multiple data 

(3) Delete a piece of data

(4) Delete multiple data

(5)Update data

(6) Update multiple pieces of data

(7) Read a certain piece of data under the condition

(8) Read a certain piece of data based on id

(9) Read multiple data

(10) Read according to query conditions

(11) Personalized reading

(12) Develop common operations

5. Graphical management


1. Basic concepts

Mongodb is a database based on distributed file storage, the official address is https://www.mongodb.com/
The main function of the database is to manage data, which can add, delete, modify, and query. The syntax is also similar to JavaScript.
Three concepts to understand before using a database
(1) Database: It is a data warehouse. For example, there are many collections under a database (can also be understood as multiple tables)
(2) Collection: table, in the JavaScript withdrawal form, it can be understood as an array [ { id: 2 , name: ultraman } ]
(3) Document: It can be understood as a piece of data. The withdrawal form in JavaScript can be understood as {id:2, name:ultraman}
For example, use js code:
{
    "users": [
        {
            "id": 1,
            "name": "张三",
            "age": 18,
        },
        {
            "id": 2,
            "name": "李四",
            "age": 20,
        },
    ],
    "articles": [
        {
            "id": 1,
            "title": "标题1",
            "content": "内容1",
        },
        {
            "id": 2,
            "title": "标题2",
            "content": "内容2",
        },
    ],

}

In the code, the entire object is a database (JSON file), which contains two collections (tables). A user table and an article table  document can be understood as data in a certain table.

Of course, there can also be multiple databases. Generally, one database is used for each project.

2. Install mongod

It is recommended to choose the zip type, which is more versatile
The configuration steps are as follows:
  1. Move the compressed package to C:\Program Files and then unzip it
  2. Create the C:\data\db directory, mongodb will save the data in this folder by default
  3. Use the bin directory in mongodb as the working directory to start the command line
  4. Run the command mongod

Since mongod needs to be run in the bin directory every time , we can configure it through environment variables.

  1. Copy the directory name, for example: C:\Program Files\mongodb-win32-x86_64-windows-5.0.19\bin
  2. Open the edit variable, find path, and append the path. 
  3. You can test it in the cmd command window next time

 3. Command interaction database

Command interaction is to interact through the cmd command line.

(1) Database commands

  Show all databases
show dbs
Switch to the specified database. If the database does not exist, the database will be automatically created.
use 数据库名

Show the current database

db

Delete current database

use 库名
db.dropDatabase()

(2) Collection command

Create a collection
db.createCollection('集合名称')

Show all collections in the current database

show collections
Delete a collection
db.集合名.drop()
Rename collection
db.集合名.renameCollection('newName')

(3) Document command

Insert document
db.集合名.insert(文档对象);

 Query document_id    is a unique number automatically generated by mongodb, which is used to uniquely identify the document.

db.集合名.find(查询条件)

 Update documentation

db.集合名.update(查询条件,新的文档)
db.集合名.update({name:'张三'},{$set:{age:19}})

Delete document

db.集合名.remove(查询条件)

 4. Mongoose

Mongoose is an object document model library, the official website is http://www.mongoosejs.net/
//1. 安装 mongoose
//2. 导入 mongoose
const mongoose = require("mongoose");
//3. 连接数据库
mongoose.connect("mongodb://127.0.0.1:27017/bilibili");
//4. 设置连接回调
//连接成功
mongoose.connection.on("open", () => {
  console.log("连接成功");
  //5. 创建文档结构对象
  let BookSchema = new mongoose.Schema({
    title: String,
    author: String,
    price: Number,
  });
  //6. 创建文档模型对象
  let BookModel = mongoose.model("book", BookSchema);
  //7. 插入文档
  BookModel.create(
    {
      title: "西游记",
      author: "吴承恩",
      price: 19.9,
    },
    (err, data) => {
      if (err) throw err;
      //输出 data 对象
      console.log(data);
      //8. 断开连接
      mongoose.disconnect();
    }
  );
});
//连接出错
mongoose.connection.on("error", () => {
  console.log("连接出错~~");
});
//连接关闭
mongoose.connection.on("close", () => {
  console.log("连接关闭");
});

Field Type

    title: String,
    price: Number,
    isHot: Boolean,
    category: Array,
    Date: Date,
    Buffer: Buffer,
    Mixed : mongoose.Schema.Types.Mixed, // 接收所有类型
    ObjectId: mongoose.Schema.Types.ObjectId, // 主键 对象ID 用来查询其他表
    Decimal:  mongoose.Schema.Types.Decimal128, // 高精度类型

Some keys can also be written in the form of objects for field verification.

(1) Required items

title: {
    type: String,
    required: true // 设置必填项
}

 (2) Default value

author: {
    type: String,
    default: '匿名' //默认值
}

(3) Enumeration value

gender: {
    type: String,
    enum: ['男','女'] //设置的值必须是数组中的
}

(4) Unique value

username: {
    type: String,
    unique: true
}
unique needs to rebuild the collection to be effective

(1) Add a piece of data

mongoose.connection.on("open", () => {
    console.log("连接成功");
    let BookSchema = new mongoose.Schema({
        title: String,
        author: String,
        price: Number
    });

    let BookModel = mongoose.model('book', BookSchema);

    BookModel.create({
        title: "《水浒传》",
        price: 15,
    }).then((res) => {
        console.log(res);
        console.log("保存成功!");
    })
   
});

Next, use model.operation as code

(2) Insert multiple data 

 BookModel.insertMany([
        {
            title: "《水浒传》",
            price: 15,
            isHot: true
        },
        {
            title: "《西游记》",
            price: 20,
            isHot: true
        }
    ]).then((res) => {
        console.log(res);
        console.log("保存成功!");
    })

(3) Delete a piece of data

 BookModel.deleteOne({ _id: "64c604fb363d6aa46652f368" }).then((res) => { 
        console.log(res);
        console.log("删除成功!");
    })

(4) Delete multiple data

Delete all if isHot is false

  BookModel.deleteMany({ isHot: false }).then((res) => {
        console.log(res);
        console.log("删除多个成功!");
    })

(5)Update data

Parameter 1: condition, parameter 2 update content

    BookModel.updateOne({ _id: "64c604fb363d6aa46652f362" },{price:99}).then((res) => { 
        console.log(res);
        console.log("更新成功!");
    })

(6) Update multiple pieces of data

    BookModel.updateMany({ isHot: true, },{isHot:false}).then((res) => {
        console.log(res);
        console.log("更新多个成功!");
    })

(7) Read a certain piece of data under the condition

     BookModel.findOne({ _id: "64c604fb363d6aa46652f362" }).then((res) => { 
        console.log("读取成功!",res);
    })

(8) Read a certain piece of data based on id

  BookModel.findById("64c604fb363d6aa46652f362").then((res) => { 
        console.log("读取成功!",res);
    })

(9) Read multiple data

   BookModel.find({ isHot: false, }).then((res) => {
        console.log("读取多个成功!",res);
    })

(10) Read according to query conditions

Some conditions cannot be judged using > < =, and must have relative command symbols.

  •  > Use $gt
  •  < use $lt
  • >= use $gte
  •  <= use $lte
  • !== use $ne

Here are some examples of operational judgments:

    // 1.多个条件的查询 价格大于20 并且 isHot 为 false
    BookModel.find({ price: { $gt: 20 }, isHot: false }).then((res) => {
        console.log("价格大于20的", res);
    })
    
    // 2.多个条件的查询都要满足 价格大于20 或者 isHot 为 false
    BookModel.find({ $and: [{ price: { $gt: 20 } }, { isHot: false }] }).then((res) => {
        console.log("价格大于20的", res);   
    })
    

    // 3.多个条件的查询满足一个 价格大于20 或者 isHot 为 false
    BookModel.find({ $or: [{ price: { $gt: 20 } }, { isHot: true }] }).then((res) => {
        console.log("价格大于20的", res);
     })

    // 4. 查询价格在 20 - 30 之间的数据
    BookModel.find({ price: { $gte: 20, $lte: 30 } }).then((res) => {
        console.log("价格大于20的", res);
    })

    // 5.正则查询
    BookModel.find({ title: { $regex: /三国/ } }).then((res) => {
        console.log("查询包含三国的", res);
    })

(11) Personalized reading

After searching, you can also perform subsequent operations through chain calls, which are also encapsulated by Promise.

  // 1.只读取出数据的某些字段
    BookModel.find().select({title:1,price:1,_id:0}).then((res) => {
        console.log("筛选结果", res);
    })
    
    // 2.排序 1 升序 -1 降序
    BookModel.find().select({title:1,price:1,_id:0}).sort({price:1}).then((res) => {
        console.log("筛选结果", res);
    })
    
    // 3.数据截取
    BookModel.find().select({title:1,price:1,_id:0}).limit(2).then((res) => {
        console.log("筛选结果", res);
    })
    
    // 4.截取3-4条
    BookModel.find().select({title:1,price:1,_id:0}).skip(2).limit(2).then((res) => {
        console.log("筛选结果", res);
    })

(12) Develop common operations

 // 登录
  login: async ({ username, password }) => {
    return UserModel.find({ username, password });
  },

  // 更新个人用户信息
  updateUserInfo: async (info) => {
    // 如果没有上传头像,就删除avatar字段 就不更新了
    if (info.image == "") delete info.image;
    return UserModel.updateOne({ _id: info.id }, info)
      .then((res) => {
        return UserModel.findOne({ _id: info.id });
      })
      .catch((err) => {
        console.log("修改失败了", err);
      });
  },

  // 获取用户列表
  getUserList: async ({ pageSize = 10, pageNum = 1, keyword = "" }) => {
    return {
      code: 200,
      msg: "获取成功",
      data: {
        pageNum: pageNum,
        pageSize: pageSize,
        total: await UserModel.find({
          username: { $regex: keyword },
        }).countDocuments(),
        userList: await UserModel.find({ username: { $regex: keyword } })
          .select("-password")
          .skip((pageNum - 1) * pageSize)
          .limit(pageSize),
      },
    };
  },

  // 添加用户
  addUser: async (info) => {
    return UserModel.find({ username: info.username }).then((res) => {
      console.log("res", res);
      if (res.length) {
        return { code: 500, msg: "用户名已存在" };
      } else {
        UserModel.create(info);
        return { code: 200, msg: "添加成功", data: { userInfo: info } };
      }
    });
  },

  // 删除用户
  deleteUser: async (info) => {
    return UserModel.deleteOne({ _id: info.id }).then((res) => {
      console.log(res, "res");
      if (res.deletedCount) {
        return { code: 200, msg: "删除成功" };
      } else {
        return { code: 500, msg: "删除失败" };
      }
    });
  },

  // 更新用户信息
  updateUser: async (info) => {
    if (info.password == "") delete info.password;
    return UserModel.updateOne({ _id: info._id }, info)
      .then((res) => {
        console.log(res, "res");
        if (res.modifiedCount) {
          return { code: 200, msg: "更新成功" };
        } else {
          return { code: 500, msg: "更新失败" };
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

5. Graphical management

Navicat charges (you can go to a certain site to install the cracked version tutorial)  https://www.navicat.com.cn/

 

Guess you like

Origin blog.csdn.net/m0_46846526/article/details/132173635