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

เปลี่ยน Data Type ของ Field ใน MongoDB (String → Int)

Aggregation ไม่สามารถเปลี่ยน Data Type ของ Field ใน Database ได้โดยตรง ต้องเขียน Script วนลูปอ่าน-แปลง-เขียนกลับ

สร้างข้อมูลตัวอย่าง


> db.changeDataType.insertOne({"StudentName":"Larry","StudentAge":23,"StudentZipCode":"10001","isProgrammer":false});
{ "acknowledged" : true, "insertedId" : ObjectId("5c6ed4976fd07954a4890694") }

ตรวจสอบ Type ของแต่ละ Field


> checkType = db.changeDataType.findOne();
> typeof checkType._id;          // "object"
> typeof checkType.StudentName;  // "string"
> typeof checkType.StudentAge;   // "number"
> typeof checkType.StudentZipCode; // "string"  ← ต้องการเปลี่ยนเป็น number
> typeof checkType.isProgrammer; // "boolean"

Script แปลง StudentZipCode จาก String เป็น Number


> db.changeDataType.find().forEach(function(doc) {
    db.changeDataType.update(
        {"_id": doc._id},
        {$set: {"StudentZipCode": parseInt(doc.StudentZipCode)}}
    );
});

ตรวจสอบ Type ใหม่


> againCheckType = db.changeDataType.findOne();
> typeof againCheckType.StudentZipCode;  // "number" ✓

แสดงเอกสารหลังแปลง


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

{ "_id" : ObjectId("5c6ed4976fd07954a4890694"), "StudentName" : "Larry", "StudentAge" : 23, "StudentZipCode" : 10001, "isProgrammer" : false }

Field StudentZipCode เปลี่ยนจาก String "10001" เป็น Number 10001 แล้ว

แนะนำ: สำหรับข้อมูลเยอะ ใช้ updateMany ร่วม $toInt (MongoDB 4.0+) ใน Aggregation Pipeline แทนการ forEach จะเร็วกว่ามาก
db.collection.updateMany(
    {},
    [{$set: {"StudentZipCode": {$toInt: "$StudentZipCode"}}}]
);