04.基本增删改查
# 01.增删改查
# 1.1 插入数据
- 1.插入文档: insert 如果插入数据的时候,collection还不存在,自动创建集合
- 2.
insertOne
: 插入一条数据 - 3.
insertMany
: 接收数组,插入多条文档
#1、插入单条数据
db.student1.insertOne({_id:"stu001","name":"Tom","age":25,grade:{"chinese":80,"math":90,"english":88}})
#2、插入多条数据
db.student1.insertMany([
{_id:"stu002","name":"Mary","age":23,grade:{"chinese":80,"math":90}},
{_id:"stu003","name":"Mike","age":23,grade:{"chinese":81,"math":90,"english":88}}
]);
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 1.2 更新文档
- updateOne和updateMany
#1、更新_id=7839的薪水 ---> 8000
db.emp.updateOne({"_id":7839},{$set:{"sal":8000}})
db.emp.find({"_id":7839}) # 查询id=7893的文档
#2、更新多条数据:更新10号部门的员工薪水,加100块钱
错误:db.emp.updateMany({"deptno":{$eq:10}},{$set:{"sal":"sal"+100}}) ---> 不对
正确:db.emp.updateMany({"deptno":{$eq:10}},{$inc:{"sal",100}})
1
2
3
4
5
6
7
2
3
4
5
6
7
# 1.3 删除文档
- deleteOne和deleteMany
db.emp.deleteOne({"_id":7839})
1
# 1.4 批处理
- 注: 为了提高效率,db.collection.bulkWrite,支持:insert update remove 同时也支持insertMany
db.mystudents.bulkWrite([
{insertOne:{"document":{"_id":100,"name":"Tom","age":25}}},
{insertOne:{"document":{"_id":101,"name":"Mary","age":24}}},
{updateOne:{"filter":{"_id":100},"update":{$set:{"name":"Tom123"}}}}
]);
1
2
3
4
5
2
3
4
5
上次更新: 2024/4/1 16:53:26