Computer >> Máy Tính >  >> Lập trình >> MongoDB

Kiểm tra trường có tồn tại bằng MongoDB không?

Bạn có thể sử dụng toán tử $ being và $ ne cho việc này. Để hiểu thêm về khái niệm này, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với tài liệu như sau -

> db.checkFieldExistDemo.insertOne({"EmployeeId":1,"EmployeeName":"John","isMarried":true,"EmployeeSalary":4648585});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76f7b31e9c5dd6f1f78281")
}
> db.checkFieldExistDemo.insertOne({"StudentId":2,"StudentName":"John","isMarried":false," StudentAge":19});
{
   "acknowledged" : true,0
   "insertedId" : ObjectId("5c76f7e11e9c5dd6f1f78282")
}

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 (). Truy vấn như sau -

> db.checkFieldExistDemo.find().pretty();

Đầu ra

{
   "_id" : ObjectId("5c76f7b31e9c5dd6f1f78281"),
   "EmployeeId" : 1,
   "EmployeeName" : "John",
   "isMarried" : true,
   "EmployeeSalary" : 4648585
}
{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}

Đây là truy vấn để kiểm tra xem trường có tồn tại trong MongoDB hay không.

Trường hợp 1 - Khi một trường có trong nhiều tài liệu. Truy vấn như sau -

> db.checkFieldExistDemo.find({"isMarried":{$exists:true,$ne:null}}).pretty();

Đầu ra

{
   "_id" : ObjectId("5c76f7b31e9c5dd6f1f78281"),
   "EmployeeId" : 1,
   "EmployeeName" : "John",
   "isMarried" : true,
   "EmployeeSalary" : 4648585
}
{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}

Trường hợp 2 - Khi một trường chỉ có trong một tài liệu. Truy vấn như sau -

> db.checkFieldExistDemo.find({"StudentName":{$exists:true,$ne:null}}).pretty();

Đầu ra

{
   "_id" : ObjectId("5c76f7e11e9c5dd6f1f78282"),
   "StudentId" : 2,
   "StudentName" : "John",
   "isMarried" : false,
   "StudentAge" : 19
}