Để lọc tài liệu dựa trên độ dài của trường chuỗi, sử dụng Regular Expression (regex).
Cú pháp regex độ dài:
db.yourCollectionName.find({
'yourFieldName': { $regex: /^.{minLength,maxLength}$/ }
});
Ví dụ: Collection queryLengthDemo với tên học sinh:
> db.queryLengthDemo.insertOne({"StudentFullName":"John Smith"}); // 10 ký tự
> db.queryLengthDemo.insertOne({"StudentFullName":"John Doe"}); // 8 ký tự
> db.queryLengthDemo.insertOne({"StudentFullName":"David Miller"}); // 12 ký tự
> db.queryLengthDemo.insertOne({"StudentFullName":"Robert Taylor"}); // 13 ký tự
> db.queryLengthDemo.insertOne({"StudentFullName":"Chris Williams"}); // 14 ký tự
Tìm tên có độ dài từ 9 đến 12 ký tự:
> db.queryLengthDemo.find({
StudentFullName: { $regex: /^.{9,12}$/ }
}).pretty();
Kết quả:
{ "_id": ..., "StudentFullName": "John Smith" } // 10 ký tự
{ "_id": ..., "StudentFullName": "David Miller" } // 12 ký tự
Giải thích regex:
^: Bắt đầu chuỗi..{9,12}: Bất kỳ ký tự nào, lặp 9 đến 12 lần.$: Kết thúc chuỗi.
Lưu ý: Regex không dùng index (collection scan), chậm trên dữ liệu lớn. Cân nhắc lưu độ dài vào trường riêng và index trường đó.