MongoDB Data Manipluations
文档插入
insert()语句可用于将单个文档插入到集合中:
db.department.insert(
{ "name":"School of Computing and Information Technology",
"code":"SCIT",
"total_staff_number":30,
"budget":1000000,
"address":{"street":"Er xian qiao street",
"bldg":3,
"city":"Chengdu",
"country":"China"},
}
)
也可以在一次调用中插入多个文档:
db.department.insert(
[ { "_id":1,
"name":"School of Computing and Information Technology",
"code":"SCIT",
"total_staff_number":30,
"budget":1000000 },
{ "_id":2,
"name":"School of Electrical Engineering",
"code":"SENG",
"total_staff_number":20,
"budget":100000 },
]
)
在上面的例子中,我们需要自己给每个文档定义id。
良好的排版习惯也很重要,合理的对齐可以在插入报错的情况下即使发现错误所在(比如括号的丢失)。
插入的限制:
- 无法在同一个集合中插入两个具有相同“_id”的文档。我们在定义id的时候要注意这点。
- 使用一个调用插入多个文档只能在一个集合上执行。上例是在department这个集合中插入的。
- 在一次插入中可以插入的数据数量有限制(48Mb)。
- 如果用一个调用插入多个文档失败,则整个操作不会回滚(部分插入)。也就是说如果其中一个文档在插入时报错,只有那个报错的文档会插入失败,其他文档成功插入。
- 一个文档必须小于16Mb。
文档删除
remove()语句可用于从集合中删除文档。
从集合中删除所有文档:
db.department.remove({})
删除代码为SCIT的所有部门:
db.department.remove({"code":"SCIT"})
删除所有名为“School of Physics ”和代码是“SOPH”的部门:
db.department.remove({"name":"School of Physics","code":"SOPH"})
Drop 一个集合:
db.department.drop()
更新文档
用新文件取代SCIT:
db.department.update({"code":"SCIT"},
{"code":"SCSE","budget":10000})
预算增加10万:
inc=Increment ,减少同理。
db.department.update({"code":"SCIT"},
{"$inc":{"budget":100000}})
将预算改为500万:
db.department.update({"code":"SCIT"},
{"$set":{"budget":5000000}})
将预算乘两倍:
mul=Multiply
db.department.update({"code":"SCIT"},
{"$mul":{"budget":2}})
将预算重命名为abc:
db.department.update({"code":"SCIT"},
{"$rename":{"budget":"abc"}})
删除abc对:
db.department.update({"code":"SCIT"},
{"$unset":{"abc":null}})
使用当前日期创建最后一个更新对:
db.department.update({"code":"SCIT"},
{"$set":{"last update":null}})
db.department.update({"code":"SCIT"},
{"$currentDate":{"last update":true}})
从课程数组中删除第二个课程:
db.department.update({"courses.code":"SOPH103"},
{"$unset":{"courses.1.code":null}})
db.department.update({"courses.code":null},
{"$pull":{"courses":{"code":null}}})
将一个新课程插入到一个课程数组中:
db.department.update({"code":"SOPH"},
{"$push":{"courses":{"code":"001","title":"Magnetism", "credits":6}}})
MongoDB中的数据操作项目练习:
https://blog.csdn.net/Jifu_M/article/details/112617386
References
- MongoDB Reference, Database Commands, Query and Write Operation Commands.
- MongoDB Reference, Operators, Update Operators.