Để kiểm tra xem một trường trong MongoDB là [] hay {}, bạn có thể sử dụng cú pháp sau -
db.yourCollectionName.find({
"yourOuterFieldName": { "$gt": {} },
"yourOuterFieldName.0": { "$exists": false }
}); Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.checkFieldDemo.insert([
... { _id: 1010, StudentDetails: {} },
... { _id: 1011, StudentDetails: [ { StudentId: 1 } ] },
... { _id: 1012, StudentDetails: [ {} ] },
... { _id: 1013 },
... { _id: 1014, StudentDetails: null},
... { _id: 1015, StudentDetails: { StudentId: 1 } }
... ]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
}) Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.checkFieldDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : 1010, "StudentDetails" : { } }
{ "_id" : 1011, "StudentDetails" : [ { "StudentId" : 1 } ] }
{ "_id" : 1012, "StudentDetails" : [ { } ] }
{ "_id" : 1013 }
{ "_id" : 1014, "StudentDetails" : null }
{ "_id" : 1015, "StudentDetails" : { "StudentId" : 1 } } Sau đây là truy vấn để kiểm tra xem một trường trong MongoDB là [] hay {} -
> db.checkFieldDemo.find({
... "StudentDetails": { "$gt": {} },
... "StudentDetails.0": { "$exists": false }
... }); Điều này sẽ tạo ra kết quả sau -
{ "_id" : 1015, "StudentDetails" : { "StudentId" : 1 } }