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

MongoDB Aggregation: ใช้ Operator $divide สำหรับการหาร

ใช้ Aggregation Pipeline Stage $project ร่วมกับ Arithmetic Operator $divide เพื่อคำนวณการหารระหว่าง 2 ฟิลด์ตัวเลข

สร้างคอลเลกชันและข้อมูลตัวอย่าง

> db.aggregationOperatorDemo.insertOne({"FirstValue": 392883, "SecondValue": 10000000000});
{ "acknowledged": true, "insertedId": ObjectId("5cd541452cba06f46efe9f01") }

แสดงข้อมูล

> db.aggregationOperatorDemo.find().pretty();

ผลลัพธ์: 1 เอกสาร

Aggregation: หาร FirstValue ด้วย SecondValue

> db.aggregationOperatorDemo.aggregate([
  {$project: {"Value": {$divide: ["$FirstValue", "$SecondValue"]}}}
]);

ผลลัพธ์: 392883 / 10000000000 = 0.0000392883

{"_id": ObjectId("5cd541452cba06f46efe9f01"), "Value": 0.0000392883}

รายละเอียด $divide

  • Syntax: {$divide: [numerator, denominator]}
  • คืนค่าเป็น Double (Floating Point)
  • รองรับ Expression: Field Reference, Constant, หรือ Expression อื่น
  • หารด้วย 0 → ผลลัพธ์เป็น Infinity หรือ -Infinity (ไม่ Error)
  • Non-numeric Values → คืน null

Arithmetic Operators ใน Aggregation

ตัวอย่างประยุกต์: คำนวณ Percentage

db.sales.aggregate([
  {$project: {
    product: 1,
    sold: 1,
    target: 1,
    percentage: {$multiply: [{$divide: ["$sold", "$target"]}, 100]}
  }}
]);

หมายเหตุ

  • ทุก Operator รับ Array ของ Arguments (ยกเว้น Unary เช่น $abs)
  • Field Reference ใช้ "$fieldName" (Dollar Sign)
  • Constant ใช้ค่าโดยตรง: 100, 3.14
OperatorSyntaxตัวอย่าง
$add{$add: [a, b, ...]}บวกหลายค่า
$subtract{$subtract: [a, b]}ลบ a - b
$multiply{$multiply: [a, b, ...]}คูณหลายค่า
$divide{$divide: [a, b]}หาร a / b
$mod{$mod: [a, b]}Modulo a % b
$abs{$abs: a}ค่าสัมบูรณ์
$floor{$floor: a}ปัดลง
$ceil{$ceil: a}ปัดขึ้น
$round{$round: [a, precision]}ปัดทศนิยม
$sqrt{$sqrt: a}รากที่ 2
$pow{$pow: [a, b]}a^b
$exp{$exp: a}e^a
$ln{$ln: a}Natural Log
$log{$log: [a, base]}Log Base
$log10{$log10: a}Log Base 10