Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách kiểm tra trường có phải kiểu số (number) trong MongoDB

Giới thiệu

Để kiểm tra một trường có phải kiểu số (number) hay không, MongoDB cung cấp toán tử $type với giá trị "number" hoặc 1 (BSON type code cho double).

Cú pháp

// Dùng tên kiểu (khuyên dùng - dễ đọc)
db.collection.find({ tenTruong: { $type: "number" } });

// Dùng BSON type code
db.collection.find({ tenTruong: { $type: 1 } }); // 1 = double

// Kiểm tra nhiều kiểu số
db.collection.find({ tenTruong: { $type: ["int", "long", "double", "decimal"] } });

Ví dụ minh họa

1. Tạo dữ liệu với các kiểu khác nhau

> db.kiemTraSo.insertOne({ "TenSinhVien": "John", "TuoiSinhVien": 23 });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec75dd628fa4220163b83") }
> db.kiemTraSo.insertOne({ "TenSinhVien": "Chris", "DiemToan": 98, "QuocGia": "US" });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec77cd628fa4220163b84") }
> db.kiemTraSo.insertOne({ "TenSinhVien": "Robert", "QuocGia": "AUS" });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec7a4d628fa4220163b85") }
> db.kiemTraSo.insertOne({ "MaSinhVien": 101, "TenSinhVien": "Larry", "QuocGia": "AUS" });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ec7ccd628fa4220163b86") }

2. Tìm doc có trường DiemToan là số

> db.kiemTraSo.find({ DiemToan: { $type: "number" } }).pretty();

3. Kết quả - chỉ tài liệu của Chris có DiemToan = 98 (số)

{ "_id" : ObjectId("5c9ec77cd628fa4220163b84"), "TenSinhVien" : "Chris", "DiemToan" : 98, "QuocGia" : "US" }

Bảng các kiểu số trong MongoDB (BSON Types)

Tên kiểuCodeMô tảVí dụ
double1Số thực 64-bit (mặc định JS)3.14, 42
int / 32-bit integer16Số nguyên 32-bit có dấuNumberInt(42)
long / 64-bit integer18Số nguyên 64-bit có dấuNumberLong("9223372036854775807")
decimal / 128-bit decimal19Số thập phân chính xácNumberDecimal("3.14")

Query kết hợp nhiều kiểu số

// Tìm doc mà "tuoi" là bất kỳ kiểu số nào
db.collection.find({ 
    tuoi: { $type: ["double", "int", "long", "decimal"] } 
});

// Hoặc dùng alias "number" (MongoDB 3.2+) - bao gồm double, int, long, decimal
db.collection.find({ 
    tuoi: { $type: "number" } 
});

Lưu ý quan trọng

  • JavaScript Number mặc định là **double** (64-bit float)
  • MongoDB shell: NumberInt(42) tạo int32, NumberLong(42) tạo int64
  • $type: "number" match: double, int, long, decimal (KHÔNG match string "123")
  • Để tìm string chứa số: { $regex: /^\d+$/ }

Ví dụ thực tế: Làm sạch dữ liệu

// Tìm doc có "gia" KHÔNG phải số (cần sửa)
db.sanPham.find({ gia: { $not: { $type: "number" } } });

// Cập nhật: chuyển string số thành double
db.sanPham.updateMany(
    { gia: { $type: "string" } },
    [{ $set: { gia: { $toDouble: "$gia" } } }] // MongoDB 4.2+ pipeline update
);