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

แปลงสตริงเป็นตัวเลข (Integer) ใน MongoDB

ใช้ parseInt() ใน JavaScript ร่วมกับ forEach() และ save() เพื่ออัปเดตค่าสตริงเป็นตัวเลขในทุกเอกสาร

ตัวอย่างข้อมูลทดสอบ (ราคาเป็นสตริง)

> db.demo369.insertOne({"Price":"1000000"});
> db.demo369.insertOne({"Price":"1747864"});
> db.demo369.insertOne({"Price":"19548575"});

แสดงข้อมูลก่อนแปลง

> db.demo369.find();
{
    "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : "1000000"
}
{
    "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : "1747864"
}
{
    "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : "19548575"
}

คำสั่งแปลงและบันทึก

> db.demo369.find().forEach(function(d) {
    d.Price = parseInt(d.Price);
    db.demo369.save(d);
});

ผลลัพธ์หลังแปลง (Price เป็น Number)

> db.demo369.find();
{
    "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : 1000000
}
{
    "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : 1747864
}
{
    "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : 19548575
}

ทางเลือก Aggregation (MongoDB 4.0+): ใช้ $toInt หรือ $convert ใน pipeline เพื่อแปลงแบบไม่ต้องวนลูป