Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Đánh giá một hoặc nhiều giá trị từ collection MongoDB

Sử dụng toán tử $or trong find() để lọc document thỏa mãn một trong các điều kiện. Tạo collection:

> db.demo174.insertOne({ "StudentName": "Chris", "CountryName": "US" });
{ "acknowledged": true, "insertedId": ObjectId("5e383c709e4f06af551997e5") }
> db.demo174.insertOne({ "StudentName": "David", "CountryName": "UK" });
{ "acknowledged": true, "insertedId": ObjectId("5e383c779e4f06af551997e6") }
> db.demo174.insertOne({ "StudentName": "Bob", "CountryName": "AUS" });
{ "acknowledged": true, "insertedId": ObjectId("5e383c7e9e4f06af551997e7") }

Hiển thị document:

> db.demo174.find();

Kết quả.

Truy vấn lấy document có StudentName="David" HOẶC CountryName="US":

> db.demo174.find({ $or: [ { "StudentName": "David" }, { "CountryName": "US" } ] });

Kết quả (2 document khớp):

{
  "_id": ObjectId("5e383c709e4f06af551997e5"),
  "StudentName": "Chris", "CountryName": "US"
}
{
  "_id": ObjectId("5e383c779e4f06af551997e6"),
  "StudentName": "David", "CountryName": "UK"
}