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

MongoDB: แปลง String ที่มีคอมมาเป็น Double ด้วย Aggregate

ใช้ aggregation pipeline ร่วม $convert, $reduce, $split, $concat เพื่อแปลง string ที่มีคอมมา (เช่น "1,533.07") เป็น double สร้างคอลเลกชันตัวอย่าง:

> db.demo335.insertOne({"Value":"45,67,78.0"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e522a1cf8647eb59e562091") }
> db.demo335.insertOne({"Value":"17664,76,534.0"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e522a26f8647eb59e562092") }
> db.demo335.insertOne({"Value":"8899,322,135,875.50"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e522a34f8647eb59e562093") }
> db.demo335.insertOne({"Value":"1,533.07"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e522ab9f8647eb59e562094") }

แสดงข้อมูล:

> db.demo335.find();

คิวรีแปลง string เป็น double:

db.demo335.aggregate([
  { $project: {
    data: {
      $convert: {
        input: {
          $reduce: {
            input: { $split: ['$Value', ','] },
            initialValue: '',
            in: { $concat: ['$$value', '$$this'] }
          }
        }
      },
      to: 'double',
      onError: 0
    }
  }}
])

ผลลัพธ์:

{ "_id" : ObjectId("5e522a1cf8647eb59e562091"), "data" : 456778 }
{ "_id" : ObjectId("5e522a26f8647eb59e562092"), "data" : 1766476534 }
{ "_id" : ObjectId("5e522a34f8647eb59e562093"), "data" : 8899322135875.5 }
{ "_id" : ObjectId("5e522ab9f8647eb59e562094"), "data" : 1533.07 }

คำอธิบาย Pipeline

  1. $split: ['$Value', ',']: ตัด string ด้วยคอมมา → array of strings
  2. $reduce: รวม array elements ด้วย $concat → string ไม่มีคอมมา
  3. $convert: แปลง string เป็น double, onError: 0 คืนค่า 0 หากแปลงไม่ได้

วิธีง่ายกว่า (MongoDB 4.0+)

ใช้ $replaceAll (MongoDB 4.4+): {$replaceAll: {input: "$Value", find: ",", replacement: ""}} แล้วตามด้วย $toDouble