Source: MongoDB University https://university.mongodb.com/
Course: M001 MongoDB bascis
【Chapter3】: Creating and Manipulating Documents
Key points:
1.Inserting New Documents - insert() and errors
2.Inserting New Documents - insert() Order
3.Updateing Documents - Data Explorer
4.Updating Documents - mongo shell
5.Deleting Documents and Collections
#------------------------
连接MongoDB
1.在mongo shell中连接数据库
1)cmd界面输入下面这行连接数据库,输入账号密码
mongo "mongodb+srv://sandbox.*****.mongodb.net/<dbname>" --username m001-student
2)连接成功,即可在命令行输入语句操作数据。
常用语句如下:
show dbs // 显示数据库名称
use sample_training //使用其中sample_training的数据库
use collections // 显示sample_trainging 里面的表格
db.inspections.findOne(); //获inspections表中中任意数据
db.inspections.find().pretty() //将inspections中全部数据已更可读的格式展示出来(用了pretty()函数)
db.inspections.find({ "city": "HUDSON" }).count() //统计 inspections表格中,city = HUDSON的数据有多少行,
1 & 2 Inserting New Documents - insert() & errors & Order
下面以pet表格为例子
插入数据:
db.pet.insert( {"_id":1,"pet":"cat"}, {"_id":2,"pet":"dog"},{"_id":3,"pet":"sheep"})
即插入了3条数据,如果不定义"_id" 唯一标识列,则系统会自己生成该行。
如果自定义的_id有重复的情况
情况1:"_id":1 出现两次
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.pet.insert([ {"_id":1,"pet":"cat"}, {"_id":1,"pet":"dog"},{"_id":3,"pet":"sheep"}])
运行结果显示:只插入了一行数据,因为第二行数据中"_id":1 重复,则程序不再往下进行了
写插入数据的语句时候,记得" [ ]" 用方括号将插入的数据包括在内。
情况2:"_id":1 出现两次,后面语句加上{"ordered":false}。插入数据之前将pet表删掉重新插入数据。
db.pet.drop()
db.pet.insert([{"_id":1,"pet":"cat"},{"_id":1,"pet":"dog"},{"_id":2,"pet":"chicken"}],{"ordered":false})
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.pet.insert([{"_id":1,"pet