Đánh giá một hoặc nhiều biểu thức bằng cách sử dụng toán tử $ hoặc trong MongoDB. Sau đây là cú pháp -
db.yourCollectionName.find({ $or: [{ "yourFieldName": yourValue1 }, { "yourFieldName": yourValue2} ] } ).pretty(); 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.orOperatorDemo.insertOne({"StudentNames":["John","Carol","Sam"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd6b80a6d78f205348bc61b")
}
> db.orOperatorDemo.insertOne({"StudentNames":["Robert","Chris","David"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd6b8266d78f205348bc61c")
}
> db.orOperatorDemo.insertOne({"StudentNames":["John"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd6b8346d78f205348bc61d")
} 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.orOperatorDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd6b80a6d78f205348bc61b"),
"StudentNames" : [
"John",
"Carol",
"Sam"
]
}
{
"_id" : ObjectId("5cd6b8266d78f205348bc61c"),
"StudentNames" : [
"Robert",
"Chris",
"David"
]
}
{
"_id" : ObjectId("5cd6b8346d78f205348bc61d"),
"StudentNames" : [
"John"
]
} Đây là truy vấn tới $ hoặc cú pháp toán tử -
> db.orOperatorDemo.find({ $or: [{ "StudentNames": "Carol" }, { "StudentNames": "John"} ] } ).pretty(); Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd6b80a6d78f205348bc61b"),
"StudentNames" : [
"John",
"Carol",
"Sam"
]
}
{
"_id" : ObjectId("5cd6b8346d78f205348bc61d"),
"StudentNames" : [
"John"
]
}