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

Cách sử dụng $type trong MongoDB

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+)

AliasBSON TypeNumber
"double"Double1
"string"String2
"object"Object3
"array"Array4
"binData"Binary5
"objectId"ObjectId7
"bool"Boolean8
"date"Date9
"null"Null10
"regex"Regex11
"int"32-bit Integer16
"long"64-bit Integer18
"decimal"Decimal12819
"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) } }
    );
});