Có. MongoDB index (bao gồm unique index) **lưu trữ giá trị null** như một giá trị bình thường. Nếu trường không tồn tại trong tài liệu, MongoDB coi như giá trị null khi index. Điều này ảnh hưởng đến unique constraint và sort order.
Tạo unique index và chèn dữ liệu có null
> db.demo170.createIndex({"Value":1},{unique:true});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo170.insert({"Value":100});
WriteResult({ "nInserted" : 1 })
> db.demo170.insert({"Value":null});
WriteResult({ "nInserted" : 1 })
> db.demo170.insert({"Value":90});
WriteResult({ "nInserted" : 1 })
> db.demo170.insert({"Value":78});
WriteResult({ "nInserted" : 1 })
Xem dữ liệu
> db.demo170.find();
{ "_id" : ObjectId("5e369b789e4f06af551997da"), "Value" : 100 }
{ "_id" : ObjectId("5e369b7c9e4f06af551997db"), "Value" : null }
{ "_id" : ObjectId("5e369b809e4f06af551997dc"), "Value" : 90 }
{ "_id" : ObjectId("5e369b969e4f06af551997dd"), "Value" : 78 }
Sắp xếp theo Value tăng dần (null lên đầu)
> db.demo170.find().sort({Value:1});
Kết quả
{ "_id" : ObjectId("5e369b7c9e4f06af551997db"), "Value" : null }
{ "_id" : ObjectId("5e369b969e4f06af551997dd"), "Value" : 78 }
{ "_id" : ObjectId("5e369b809e4f06af551997dc"), "Value" : 90 }
{ "_id" : ObjectId("5e369b789e4f06af551997da"), "Value" : 100 }
Hệ quả quan trọng:
- Unique index trên trường cho phép null -> **chỉ cho phép tối đa 1 tài liệu có null** (hoặc thiếu trường đó).
- Sắp xếp tăng dần: null < số âm < 0 < số dương.
- Partial Index (MongoDB 3.2+) với
partialFilterExpression: {Value: {$exists: true, $ne: null}}có thể bỏ qua null trong unique index.