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

Cách xử lý dữ liệu tùy chọn/rỗng (optional/empty) trong MongoDB

Giới thiệu

MongoDB cho phép trường (field) có giá trị null, chuỗi rỗng (""), hoặc hoàn toàn không tồn tại. Để xử lý dữ liệu tùy chọn/rỗng, bạn có thể dùng các toán tử truy vấn phù hợp.

Ví dụ minh họa

1. Tạo dữ liệu với các trường hợp rỗng

> db.xuLyRongDemo.insertOne({"TenSinhVien":"John","QuocGia":""});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9cbd5ca629b87623db1b12") }
> db.xuLyRongDemo.insertOne({"TenSinhVien":"John","QuocGia":null});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9cbd6ba629b87623db1b13") }
> db.xuLyRongDemo.insertOne({"TenSinhVien":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9cbd71a629b87623db1b14") }

2. Xem dữ liệu

> db.xuLyRongDemo.find().pretty();
{ "_id" : ObjectId("5c9cbd5ca629b87623db1b12"), "TenSinhVien" : "John", "QuocGia" : "" }
{ "_id" : ObjectId("5c9cbd6ba629b87623db1b13"), "TenSinhVien" : "John", "QuocGia" : null }
{ "_id" : ObjectId("5c9cbd71a629b87623db1b14"), "TenSinhVien" : "John" }

3. Tìm doc có QuocGia không null (vẫn trả về chuỗi rỗng)

> db.xuLyRongDemo.find({ QuocGia: { $ne: null } });
{ "_id" : ObjectId("5c9cbd5ca629b87623db1b12"), "TenSinhVien" : "John", "QuocGia" : "" }

Phân tích 3 trạng thái "rỗng"

Trạng tháiVí dụ$exists: true$ne: null$ne: ""$nin: [null,""]
Trường không tồn tại{ name: "John" }❌✅ (trả về!)✅❌
Trường = null{ name: "John", country: null }✅❌✅❌
Trường = ""{ name: "John", country: "" }✅✅❌❌
Trường có giá trị{ name: "John", country: "US" }✅✅✅✅

Các pattern xử lý phổ biến

1. Chỉ lấy doc có trường VÀ có giá trị thực (không null, không "")

db.collection.find({ 
    truong: { $exists: true, $nin: [null, ""] } 
});

2. Set default value khi truy vấn (aggregation)

db.collection.aggregate([
    { $project: { 
        tenTruong: { $ifNull: [ "$tenTruong", "DEFAULT_VALUE" ] } 
    } }
]);

3. Cập nhật: set giá trị mặc định cho trường null/rỗng

db.collection.updateMany(
    { truong: { $in: [null, ""] } },
    { $set: { truong: "DEFAULT_VALUE" } }
);

4. Schema validation (MongoDB 3.6+)

db.createCollection("users", {
    validator: {
        $jsonSchema: {
            properties: {
                email: { 
                    bsonType: "string",
                    description: "Email là bắt buộc"
                }
            },
            required: ["email"]
        }
    }
});