This entry is part 17 of 24 in the series MongoDB Kiểm tra null, check tồn tại trong MongoDB với $exists. Trong MongoDB, dữ liệu lưu ở collection không có cấu trúc dữ liệu cố định. Tức là bản ghi (document) này có field này nhưng bản ghi khác lại không có field đó. Do đó khi truy vấn, tìm kiếm theo field nào đó, ta cần phân biệt field đó null hay là không tồn tại. Ví dụ mình insert 5 bản ghi (document) sau vào collection db.player.insert([ {'_id':'1', 'name':'neymar', 'country':null, 'age':'25'}, {'_id':'2', 'name':'hazard', 'country':null, 'age':'25'}, {'_id':'3', 'name':'mbappe', 'age':'18'}, {'_id':'4', 'name':'modric', 'country':'croatia', 'age':'30'}, {'_id':'5', 'name':'ronaldo', 'country':'portugal', 'age':'33'}]) Trong đó bản ghi 1 và 2 có field Bây giờ mình sẽ thực hiện lấy ra các bản ghi (document) có db.getCollection('player').find({country: {$ne: null}}) Rõ ràng field không tồn tại cũng được tính như là field có giá trị bằng null. Tương tự ta lấy các bản ghi có country bằng null thì kết quả như sau: Kiểm tra field tồn tại trong MongoDB ($exists)Field/trường không tồn tại tương đương với giá trị bằng null, tuy nhiên nếu muốn kiểm tra chính xác field đó có tồn tại hay không thì ta phải dùng tới Ví dụ, tìm các document có chứa trường db.getCollection('player').find({country: {$exists: true}}) Kết quả: Chỉ duy nhất bản ghi có _id = 3 là không thỏa mãn. Okay, Done! References: https://docs.mongodb.com/manual/reference/operator/query/exists/ Docs Home → MongoDB Manual → MongoDB Manual ➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.Select your language drop-down menu in the upper-right to set the language of the following examples. Different query operators in MongoDB treat The query returns both documents in the collection. The query returns only the document where the db.getCollection('player').find({country: {$ne: null}})0 field has a value of null .Các truy vấn ví dụ sau đây cho các tài liệu không chứa một trường.[1] Truy vấn chỉ trả về tài liệu không chứa trường db.getCollection('player').find({country: {$ne: null}})0. MẹoXem thêm:Tài liệu tham khảo cho các toán tử db.getCollection('player').find({country: {$ne: null}})3 và $exists . |