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

หาชนิดข้อมูล (Data Type) ของทุกฟิลด์ใน MongoDB

ใช้ typeof ใน MongoDB Shell ตรวจสอบ Data Type ของ Field

ใน MongoDB Shell (JavaScript) สามารถใช้ typeof operator ตรวจสอบชนิดข้อมูลของฟิลด์ในเอกสารได้

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

> db.findDataTypeDemo.insertOne({"ClientName":"Chris","isMarried":false});

ตรวจสอบ Data Type

> typeof db.findDataTypeDemo.findOne().isMarried;
Boolean

> typeof db.findDataTypeDemo.findOne().ClientName;
String

ดูค่าจริง

> db.findDataTypeDemo.findOne().ClientName;
Chris
> db.findDataTypeDemo.findOne().isMarried;
false

JavaScript typeof vs MongoDB BSON Type

BSON Typetypeof ResultMongoDB $type Code
String"string"2 / "string"
Number (Int/Double)"number"1 / "double", 16 / "int", 18 / "long"
Boolean"boolean"8 / "bool"
Null"object"10 / "null"
Object / Array"object"3 / "object", 4 / "array"
ObjectId"object"7 / "objectId"
Date"object"9 / "date"

⚠️ ข้อสังเกตสำคัญ

  • typeof null === "object" ใน JavaScript (เป็น Bug แห่งแรกของ JS ที่คงอยู่มาจนตอนนี้)
  • typeof ObjectId() === "object"
  • typeof ISODate() === "object"
  • ใช้ $type ใน Query/Aggregation เพื่อตรวจสอบ BSON Type จริง

วิธีเช็ค Type ใน Aggregation (Server-side)

db.findDataTypeDemo.aggregate([
    { $project: {
        ClientNameType: { $type: "$ClientName" },
        isMarriedType: { $type: "$isMarried" },
        _idType: { $type: "$_id" }
    }}
]);
// Result: { "ClientNameType": "string", "isMarriedType": "bool", "_idType": "objectId" }