MongoDB 概念及增删改查
1. MongoDB基本概念
MongoDB 与 MySQL 概念对应关系
| MongoDB | MySQL |
| Database 数据库 | Database 数据库 |
| Collection 集合 | Table 表 |
| Document 文档 | Row 行 |
| Field 字段 | Column 列 |
| Index 索引 | Index 索引 |
| _id | Primary Key 主键 |
| $lookup | join |
| $group | group by |
默认结构
test: MongoDB默认空数据库,如无数据则实际未被创建。
2. 常用指令
(1)cls 清屏
(2)show databases/show dbs 陈列所有已有数据的数据库
(3)use dbs_name 切换数据库(如果数据库不存在也可以操作,但在确实添加数据之前不会建立数据库)
(4)增
(a)db.collection.insertOne({key: value, ...}) 插入一个document到collection中。成功添加返回true和insertedId(该document全局唯一ID)
(b)db.collection.insertMany([{key: value, ...}, {key:value, ...}, ...])
(c)注意:insert时值可以为null,这种情况下find $exists默认为存在会返回
(5)删
(a)db.collection.deleteOne() 删除满足条件的一条数据【条件语法查看后文】
(b)db.collection.deleteMany() 删除满足条件的多条数据
(6)改
(a)db.collection.updateOne({field: 1, ...}, {$set: {updatedField: 2}}) 找到符合第一个参数的第一条内容,第二个参数为更新的内容;更新多采用_id来定位数据进行更新
(b)db.collection.updateMany() 更新多条符合第一个参数的document
(7)查
(a)db.collection.find() 返回该collection的所有数据
(b)db.collection.find().limit(int num) 返回特定数量num的数据
(c)db.collection.find().sort({field1: 1/-1, field2: 1/-1, ...}) 排序返回, field1: 1 以field1的值升序输出,field1: -1 以field1的值降序输出; 支持以多个field排序
(d)db.collection.find().skip(int num) 跳过特定数量num的数据执行操作,可结合sort等函数使用,实现分页的功能
(e)db.collection.find({field: value}) 与SQL WHERE语句类似,返回指定field有特定值的document
(f)db.collection.find({field: value}, {field1: 1, field2: 1}) 第二个参数与SQL SELECT语句类似,只返回field有特定值的document中的field1 field2(1代表需要返回),除此之外_id默认返回,不想要_id返回要在第二个参数的{}中添加 _id: 0; 如果只是排除特定字段不返回其余返回,只需要在第二个参数的{}中添加 field3: 0, ...这样返回除了field3等字段
(g)db.collection.find({field1: {$gt: 3}, field2:{$in: [1, 2, 3]}}) 返回field1值大于3、field2在[1, 2, 3]中的document;【其他逻辑运算符:$nin:[] | $exists: true/false】【默认情况下,多个并列的条件为and连接】
(h)db.collection.find({$or: [{field1: 3}, {field2: {$gt: 2}}]}) 使用$or连接多个条件【其他:$not, $and】
(i)db.collection.find({field: {$regex: /正则表达式内容/, $options: 'i'}}) 使用正则表达式筛选内容,$options 添加其他限制条件(此处‘i’代表不区分大小写)【查看 正则附录】
(j)db.collection.countDocuments() 返回符合限制条件的document的数量
(k)db.collection.findOne()返回符合条件的第一条document

浙公网安备 33010602011771号