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":"cat"},{"_id":1,"pet":"dog"},{"_id":2,"pet":"chicken"}],{"ordered":false})
BulkWriteResult({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: sample_training.pet index: _id_ dup key: { _id: 1.0 }",
"op" : {
"_id" : 1,
"pet" : "cat"
}
},
{
"index" : 1,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: sample_training.pet index: _id_ dup key: { _id: 1.0 }",
"op" : {
"_id" : 1,
"pet" : "dog"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
结果显示,数据插入进入了,但是出现了duplicate key error
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.pet.find().pretty()
{ "_id" : 1, "pet" : "cat" }
{ "_id" : 2, "pet" : "chicken" }
查看数据,可看到即使存在error,仍然有2条数据插入进去了,第二条{"_id":1,"pet":"dog"}的数据未插入进去。
因为我们设置的 {"ordered":false},程序执行的时候,不会按照给出的数据的顺序进行插入,如果遇到error仍然会跳过插入之后key不重复的数据。
情况2:"_id":1 出现两次,后面语句加上{"ordered":true}. 插入数据之前将pet表删掉重新插入数据。
db.pet.drop()
db.pet.insert([{"_id":1,"pet":"cat"},{"_id":1,"pet":"dog"},{"_id":2,"pet":"chicken"}],{"ordered":true})
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.pet.insert([{"_id":1,"pet":"cat"},{"_id":1,"pet":"dog"},{"_id":2,"pet":"chicken"}],{"ordered":true})
BulkWriteResult({
"writeErrors" : [
{
"index" : 1,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: sample_training.pet index: _id_ dup key: { _id: 1.0 }",
"op" : {
"_id" : 1,
"pet" : "dog"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.pet.find().pretty()
{ "_id" : 1, "pet" : "cat" }
在出现duplicate key error的情况下依然插入了数据,但是只插入了一行。
因为我们设置的 {"ordered":true},程序执行的时候,会按照给出的数据的顺序进行插入,遇到error便停止。
3.Updateing Documents - Data Explorer
直接在Altas更新数据,简单易操作。查看数据,右上角点击铅笔形状的图标,即可操作数据。
4.Updating Documents - mongo shell
updateMany() 和 updateOne() 分别为更新全部数据和更新一条数据。
1)$inc -- increment filed value by aspecified amount,给指定的数据增加指定数据,可以多个同时更新。
语句如下:
{"$inc":{"<filed1":<increment value>,"<filed2>":<increment value>,....}}
例,给zips表格中,city= HUDSON的全部数据的pop列增加10,(pop列需是int或者double类型)
db.zips.updateMany({ "city": "HUDSON" }, { "$inc": { "pop": 10 } })
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.zips.find({"city":"HUDSON"}).pretty()
{
"_id" : ObjectId("5c8eccc1caa187d17ca6f9ff"),
"city" : "HUDSON",
"zip" : "80642",
"loc" : {
"y" : 40.060555,
"x" : 104.653208
},
"pop" : 2389,
"state" : "CO"
}
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.zips.updateMany({ "city": "HUDSON" }, { "$inc": { "pop": 10 } })
{ "acknowledged" : true, "matchedCount" : 16, "modifiedCount" : 16 }
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.zips.find({"city":"HUDSON"}).pretty()
{
"_id" : ObjectId("5c8eccc1caa187d17ca6f9ff"),
"city" : "HUDSON",
"zip" : "80642",
"loc" : {
"y" : 40.060555,
"x" : 104.653208
},
"pop" : 2399,
"state" : "CO"
}
我们可以 看到pop列的数据由2389,增加了10变成了2399
2)$set -- sets filed value to a new specified value,给指定的数据重置为新的数据。
语法如下:
{"$set":{"<filed1>":<new value>,"<field2>":<new value>,...}}
例:db.zips.updateOne({ "zip": "12534" }, { "$set": { "pop": 17630 } })
将zips表格中 筛选zip为12534的数据,将该数据中pop列的值更新为17630
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.zips.find({"zip":"12534"}).pretty()
{
"_id" : ObjectId("5c8eccc1caa187d17ca73239"),
"city" : "HUDSON",
"zip" : "12534",
"loc" : {
"y" : 42.246978,
"x" : 73.755248
},
"pop" : 17640,
"state" : "NY"
}
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.zips.updateOne({ "zip": "12534" }, { "$set": { "pop": 17630 } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.zips.find({"zip":"12534"}).pretty()
{
"_id" : ObjectId("5c8eccc1caa187d17ca73239"),
"city" : "HUDSON",
"zip" : "12534",
"loc" : {
"y" : 42.246978,
"x" : 73.755248
},
"pop" : 17630,
"state" : "NY"
}
从结果可以看到,将pop从17640更新为了17630
3)$push-- adds an element to an array filed 给指定的filed新增一个元素。
语法如下:
{"$push":{"<filed1>":<value1>,"<field2>":<value2>,...}}
例: 给grades表中将student_id=1,class_id=302的数据中,在scores中,新增一个type 名字为"extra credit",对应分数为100。
db.grades.updateOne({ "student_id": 1, "class_id": 302}, { "$push": { "scores": { "type": "extra credit", "score": 100 } } })
首先我们查看这个学生的成绩组成:
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.grades.find({ "student_id": 1, "class_id": 302 }).pretty()
{
"_id" : ObjectId("56d5f7eb604eb380b0d8d8e0"),
"student_id" : 1,
"scores" : [
{
"type" : "exam",
"score" : 90.8264171922822
},
{
"type" : "quiz",
"score" : 51.77230177525646
},
{
"type" : "homework",
"score" : 68.97104926017997
},
{
"type" : "homework",
"score" : 2.8270734687576238
}
],
"class_id" : 302
}
运行update命令之后,我们可以看到type中新增了一个数据叫extra credit, socre =100
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.grades.updateOne({ "student_id": 1, "class_id": 302}, { "$push": { "scores": { "type": "extra credit", "score": 100 } } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
MongoDB Enterprise atlas-mgr67a-shard-0:PRIMARY> db.grades.find({ "student_id": 1, "class_id": 302 }).pretty()
{
"_id" : ObjectId("56d5f7eb604eb380b0d8d8e0"),
"student_id" : 1,
"scores" : [
{
"type" : "exam",
"score" : 90.8264171922822
},
{
"type" : "quiz",
"score" : 51.77230177525646
},
{
"type" : "homework",
"score" : 68.97104926017997
},
{
"type" : "homework",
"score" : 2.8270734687576238
},
{
"type" : "extra credit",
"score" : 100
}
],
"class_id" : 302
}
5.Deleting Documents and Collections
1) deleteMany() 删除全部符合要求的数据
db.inspections.deleteMany({ "test": 1 })
2) deleteOne() 删除符合要求的一条数据
db.inspections.deleteOne({ "test": 3 })
3) drop() 将inspection表格删除,如果将一个数据库中的全部collection删除,那么这个数据库也会被移除。
db.inspection.drop()