Section 8: Update Operations

Module Introduction

Contents

Ta sử dụng 2 hàm là updateOne() cho việc update riêng 1 document và updateMany() là update theo nhiều documents.

Cập nhật 1 thông tin user hobbies:

{
	"_id" : ObjectId("6077361d18b9197465ca8c71"),
	"name" : "Tam",
	"age" : 31,
	"hobbies" : [
		"cookie",
		"market"
	],
	"phone" : 979029556
}
db.users.updateOne({_id: ObjectId("6077361d18b9197465ca8c71")}, {$set: {hobbies: [{title: "cookie", frequency: 2}, {title: "market", frequencty: 5}]}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Sau khi updateOne:

db.users.find({_id: ObjectId("6077361d18b9197465ca8c71")}).pretty()
{
	"_id" : ObjectId("6077361d18b9197465ca8c71"),
	"name" : "Tam",
	"age" : 31,
	"hobbies" : [
		{
			"title" : "cookie",
			"frequency" : 2
		},
		{
			"title" : "market",
			"frequencty" : 5
		}
	],
	"phone" : 979029556
}

Với updateMany, tìm kiếm các hobbies title là Sports, sau đó set isSporty: true

MongoDB Enterprise atlas-14kagn-shard-0:PRIMARY> db.users.updateMany({"hobbies.title":"Sports"}, {$set: {isSporty: true}})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
MongoDB Enterprise atlas-14kagn-shard-0:PRIMARY> db.users.find().pretty()
{
	"_id" : ObjectId("6077361d18b9197465ca8c71"),
	"name" : "Tam",
	"age" : 31,
	"hobbies" : [
		{
			"title" : "cookie",
			"frequency" : 2
		},
		{
			"title" : "market",
			"frequencty" : 5
		}
	],
	"phone" : 979029556
}
{
	"_id" : ObjectId("6077361d18b9197465ca8c72"),
	"name" : "Det",
	"age" : 32,
	"hobbies" : [
		"learning",
		"working alone"
	],
	"phone" : "0974170690"
}
{
	"_id" : ObjectId("6077361d18b9197465ca8c73"),
	"name" : "Trung",
	"age" : null
}
{
	"_id" : ObjectId("60775e551ca7f87919df6fb9"),
	"name" : "Trong",
	"age" : 25,
	"hobbies" : [
		"hoc",
		"ngu",
		"choi",
		"an"
	]
}
{
	"_id" : ObjectId("60779afc95b7602b09a1c5f1"),
	"name" : "Tien",
	"age" : 42,
	"hobbies" : [
		{
			"title" : "Sports",
			"frequency" : 2
		},
		{
			"title" : "Yoga",
			"frequency" : 3
		}
	],
	"phone" : 912321026,
	"isSporty" : true
}
{
	"_id" : ObjectId("60779f5795b7602b09a1c5f2"),
	"name" : "Lan",
	"age" : 22,
	"hobbies" : [
		{
			"title" : "Sports",
			"frequency" : 6
		},
		{
			"title" : "Yoga",
			"frequency" : 3
		}
	],
	"phone" : 912321026,
	"isSporty" : true
}

Updating Multiple Fields with
“$set”

db.users.updateOne({_id: ObjectId("6077361d18b9197465ca8c71")}, {$set: {company: "Opentechiz", address: "Tay Ho- Ha Noi"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
db.users.find({_id: ObjectId("6077361d18b9197465ca8c71")}).pretty()
{
	"_id" : ObjectId("6077361d18b9197465ca8c71"),
	"name" : "Tam",
	"age" : 31,
	"hobbies" : [
		{
			"title" : "cookie",
			"frequency" : 2
		},
		undefined,
		{
			"title" : "market",
			"frequencty" : 5
		}
	],
	"phone" : 979029556,
	"address" : "Tay Ho- Ha Noi",
	"company" : "Opentechiz"
}

. Incrementing & Decrementing
Values

Tăng thêm tuổi dùng + tuổi hiện tại. {$inc: { age: 2}}

Using “$min”, “$max” and “$mul”

$min kiểm tra theo field nếu như giá trị field mà lớn hơn $min được set thì sẽ update theo giá trị $min

MongoDB Enterprise atlas-14kagn-shard-0:PRIMARY> db.users.find({_id: ObjectId("6077361d18b9197465ca8c71")}).pretty()
{
	"_id" : ObjectId("6077361d18b9197465ca8c71"),
	"name" : "Tam",
	"age" : 30,
	"hobbies" : [
		{
			"title" : "cookie",
			"frequency" : 2
		},
		undefined,
		{
			"title" : "market",
			"frequencty" : 5
		}
	],
	"phone" : 979029556,
	"address" : "Tay Ho- Ha Noi",
	"company" : "Opentechiz"
}
db.users.updateOne({_id: ObjectId("6077361d18b9197465ca8c71")}, {$min: {age: 35}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }
db.users.find({_id: ObjectId("6077361d18b9197465ca8c71")}).pretty()
{
	"_id" : ObjectId("6077361d18b9197465ca8c71"),
	"name" : "Tam",
	"age" : 30,
	"hobbies" : [
		{
			"title" : "cookie",
			"frequency" : 2
		},
		undefined,
		{
			"title" : "market",
			"frequencty" : 5
		}
	],
	"phone" : 979029556,
	"address" : "Tay Ho- Ha Noi",
	"company" : "Opentechiz"
}

Trường hợp này ko update được do tuổi là 30 nhưng số cần update là 31

TƯơng tự $max , nếu giá trị mới cần set của $max > age tuổi hiện tại thì sẽ set giá trị mới

db.users.updateOne({_id: ObjectId("6077361d18b9197465ca8c71")}, {$max: {age: 35}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
db.users.find({_id: ObjectId("6077361d18b9197465ca8c71")}).pretty()
{
	"_id" : ObjectId("6077361d18b9197465ca8c71"),
	"name" : "Tam",
	"age" : 35,
	"hobbies" : [
		{
			"title" : "cookie",
			"frequency" : 2
		},
		undefined,
		{
			"title" : "market",
			"frequencty" : 5
		}
	],
	"phone" : 979029556,
	"address" : "Tay Ho- Ha Noi",
	"company" : "Opentechiz"
}

Với $mul là phép tính nhân thêm %.

Getting Rid of Fields

Xóa các field khỏi document. Ta dùng $unset sẽ xóa khỏi.

 Renaming Fields

Thay đổi tên 1 fireld:

Understanding “upsert()”

Hàm này có nhiệm vụ nếu như đã tồn tại dữ liệu theo điều kiên nào đó, thì nó sẽ update, còn nếu điều kiệm tìm kiếm ko có thì nó sẽ insert vào, cách sử dụng truyền vào tham số thứ 3 {upsert: true}.

Bài tập: Thêm 2 documents bằng toán tử upsert()

 db.sports.updateOne({title: "Bong da"}, {$set: {requiresTeam: true}}, {upsert: true})
{
	"acknowledged" : true,
	"matchedCount" : 0,
	"modifiedCount" : 0,
	"upsertedId" : ObjectId("6077f33484d57212061e018e")
}
db.sports.find().pretty()
{
	"_id" : ObjectId("6077f33484d57212061e018e"),
	"title" : "Bong da",
	"requiresTeam" : true
}
db.sports.updateOne({title: "Cau long"}, {$set: {requiresTeam: true}}, {upsert: true})
{
	"acknowledged" : true,
	"matchedCount" : 0,
	"modifiedCount" : 0,
	"upsertedId" : ObjectId("6077f37d84d57212061e0820")
}
db.sports.find().pretty()
{
	"_id" : ObjectId("6077f33484d57212061e018e"),
	"title" : "Bong da",
	"requiresTeam" : true
}
{
	"_id" : ObjectId("6077f37d84d57212061e0820"),
	"title" : "Cau long",
	"requiresTeam" : true
}

Cập nhật tất cả documents mà require bằng một team và thêm một trường mới là miimum số lượng của players required

db.sports.updateMany({requiresTeam:true},{$set:{minimumAmountOfPlayersRequired:null}})

db.sports.updateMany({requiresTeam:true},{$inc:{minimumAmountOfPlayersRequired:10}})

Updating Matched Array Elements

db.users.updateMany({"hobbies": {$elemMatch: {title: "Sports", frequency: {$gte: 3}}}}, {$set: {"hobbies.$.highFrequency": true}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Câu lệnh trên sẽ tìm kiếm các documents match với biểu thức tham số thứ nhất, và sẽ set thêm trường hightFrequency: true nếu tìm đúng

 db.users.find({"hobbies": {$elemMatch: {title: "Sports", frequency: {$gte: 3}}}}).pretty()
{
	"_id" : ObjectId("60779f5795b7602b09a1c5f2"),
	"name" : "Lan",
	"age" : 23,
	"hobbies" : [
		{
			"title" : "Sports",
			"frequency" : 6,
			"highFrequency" : true
		},
		{
			"title" : "Yoga",
			"frequency" : 3
		}
	],
	"phone" : 979029556,
	"isSporty" : true
}

Updating All Array Elements

Update các user có tuổi lớn hơn 30, và sẽ tiến hành -1 trong mảng hobbies qua hobbies.$[].frequency

MongoDB Enterprise atlas-14kagn-shard-0:PRIMARY> db.users.updateMany({age:{$gt: 30}}, {$inc: {"hobbies.$[].frequency": -1}})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

Finding & Updating Specific Fields

db.users.updateMany({"hobbies.frequency": {$gt: 2}}, {$set: {"hobbies.$[el].goodFrequency1": true}}, {arrayFilters: [{"el.frequency": {$gt: 2}}]})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Adding Elements to Arrays

 Removing Elements from Arrays

Xóa element cuối cùng trong mảng.

Xóa phần tử đầu mảng .

. Understanding “$addToSet”

$addtoSet dùng để thêm duy nhất giá trị vào document

Trước khi thêm

Khi thêm một hobbies vào array

https://docs.mongodb.com/manual/tutorial/update-documents/

2 Comments on “Section 8: Update Operations

Leave a Reply

%d bloggers like this: