Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

การลบค่า (TotalPrice - Discount) จากค่าฟิลด์เอกสารใน MongoDB


เพื่อลบค่าจากค่าฟิลด์เอกสาร ให้ใช้ $subtract ใน MongoDB aggregate() มาสร้างคอลเล็กชันกันเถอะ

> db.demo599.insertOne({"TotalPrice":250,"DiscountPrice":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e948192f5f1e70e134e2696") }
> db.demo599.insertOne({"TotalPrice":400,"DiscountPrice":10});
{ "acknowledged" : true, "insertedId" : ObjectId("5e948199f5f1e70e134e2697") }
> db.demo599.insertOne({"TotalPrice":1550,"DiscountPrice":50});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9481a0f5f1e70e134e2698") }

แสดงเอกสารทั้งหมดด้วยเมธอด find()

> db.demo599.find();

ผลลัพธ์ที่ได้

{ "_id" : ObjectId("5e948192f5f1e70e134e2696"), "TotalPrice" : 250, "DiscountPrice" : 35 }
{ "_id" : ObjectId("5e948199f5f1e70e134e2697"), "TotalPrice" : 400, "DiscountPrice" : 10 }
{ "_id" : ObjectId("5e9481a0f5f1e70e134e2698"), "TotalPrice" : 1550, "DiscountPrice" : 50 }

คำสั่งลบค่าจากค่าฟิลด์เอกสาร (TotalPrice - DiscountPrice)

> db.demo599.aggregate( [ { $project: {ActualPrice: { $subtract: [ "$TotalPrice", "$DiscountPrice" ] } } } ] )

ผลลัพธ์ที่ได้

{ "_id" : ObjectId("5e948192f5f1e70e134e2696"), "ActualPrice" : 215 }
{ "_id" : ObjectId("5e948199f5f1e70e134e2697"), "ActualPrice" : 390 }
{ "_id" : ObjectId("5e9481a0f5f1e70e134e2698"), "ActualPrice" : 1500 }