Truy vấn theo kiểu dữ liệu BSON với toán tử $type
$type chọn document nơi giá trị trường là instance của kiểu BSON chỉ định (string, int, double, array, object...).
1. Dữ liệu: Field Value hỗn hợp kiểu
> db.demo615.insert({ Value: 100 }); // Int32
> db.demo615.insert({ Value: "100" }); // String
> db.demo615.insert({ Value: "300" }); // String
> db.demo615.insert({ Value: 300 }); // Int32
2. Chỉ lấy Value là String
> db.demo615.find({ Value: { $type: "string" } });
3. Kết quả
{ "_id": ObjectId("5e99bb3865492f6c60d00280"), "Value": "100" }
{ "_id": ObjectId("5e99bb3c65492f6c60d00281"), "Value": "300" }
Các alias $type phổ biến (MongoDB 3.2+)
| Alias | BSON Type | Number |
|---|---|---|
| "double" | Double | 1 |
| "string" | String | 2 |
| "object" | Object | 3 |
| "array" | Array | 4 |
| "binData" | Binary | 5 |
| "objectId" | ObjectId | 7 |
| "bool" | Boolean | 8 |
| "date" | Date | 9 |
| "null" | Null | 10 |
| "regex" | Regex | 11 |
| "int" | 32-bit Integer | 16 |
| "long" | 64-bit Integer | 18 |
| "decimal" | Decimal128 | 19 |
| "number" | Double, Int, Long | - |
Sử dụng số hiệu type (legacy)
// Tương đương nhau:
db.demo615.find({ Value: { $type: 2 } }); // Number alias
db.demo615.find({ Value: { $type: "string" } }); // String alias (khuyến khích)
Kết hợp nhiều kiểu
// Lấy Value là string HOẶC int
db.demo615.find({ Value: { $type: ["string", "int"] } });
// Lấy Value KHÔNG phải string
db.demo615.find({ Value: { $not: { $type: "string" } } });
// Hoặc
db.demo615.find({ Value: { $type: { $nin: ["string"] } } });
Ứng dụng thực tế
- Data cleaning: Tìm field sai kiểu (số lưu thành string, date lưu thành string...)
- Schema validation: Kiểm tra collection schema-less
- Migration: Xác định document cần convert kiểu
- Polymorphic queries: Xử lý khác nhau theo kiểu dữ liệu
Ví dụ: Chuyển đổi string số thành int
// 1. Tìm string number
var cursor = db.demo615.find({ Value: { $type: "string", $regex: /^\d+$/ } });
// 2. Cập nhật từng doc (shell)
cursor.forEach(doc => {
db.demo615.updateOne(
{ _id: doc._id },
{ $set: { Value: parseInt(doc.Value) } }
);
});