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

Triển khai toán tử OR trong find() MongoDB

Toán tử $or cho phép truy vấn document thỏa mãn ít nhất một trong nhiều điều kiện.

Tạo collection

> db.demo78.insertOne({"Name1":"Chris","Name2":"Mike"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd99c71bf0181ecc4228f") }
> db.demo78.insertOne({"Name1":"Bob","Name2":"Carol"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd9ac71bf0181ecc42290") }
> db.demo78.insertOne({"Name1":"David","Name2":"Sam"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd9b671bf0181ecc42291") }
> db.demo78.insertOne({"Name1":"Jace","Name2":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd9bf71bf0181ecc42292") }

Truy vấn $or

Tìm document có Name1="Bob" HOẶC Name2="John":

> db.demo78.find({$or: [{"Name1": "Bob"}, {Name2: "John"}] });

Kết quả

{ "_id" : ObjectId("5e2bd9ac71bf0181ecc42290"), "Name1" : "Bob", "Name2" : "Carol" }
{ "_id" : ObjectId("5e2bd9bf71bf0181ecc42292"), "Name1" : "Jace", "Name2" : "John" }

Lưu ý:

  • $or nhận một mảng các điều kiện
  • Mỗi điều kiện trong mảng là một object truy vấn hoàn chỉnh
  • Có thể kết hợp với $and cho logic phức tạp: {$and: [{$or: [...]}, {status: "active"}]}
  • Để tối ưu hiệu suất, hãy tạo index cho các trường trong $or