ใช้ $or รวมเงื่อนไขหลายอย่างใน Query/Update/Remove
โอเปอเรเตอร์ $or ทำ Logical OR ระหว่างเงื่อนไขหลายตัว - Match ถ้าตรง อย่างน้อย 1 เงื่อนไข
ตัวอย่างข้อมูล
> db.multipleConditionDemo.insertOne({"_id":1,"Name":"John"});
> db.multipleConditionDemo.insertOne({"_id":2,"Name":"Carol"});
> db.multipleConditionDemo.insertOne({"_id":3,"Name":"Sam"});
> db.multipleConditionDemo.insertOne({"_id":4,"Name":"David"});
คำสั่งลบเอกสารที่ _id เป็น 2 หรือ 3
> db.multipleConditionDemo.remove({ $or: [ { _id: 2 }, { _id: 3 } ] });
WriteResult({ "nRemoved" : 2 })
ผลลัพธ์: เหลือ _id 1 และ 4
> db.multipleConditionDemo.find().pretty();
{ "_id" : 1, "Name" : "John" }
{ "_id" : 4, "Name" : "David" }
Logical Operators ใน MongoDB
| Operator | ความหมาย | Syntax |
|---|---|---|
$or | OR - ตรงอย่างน้อย 1 | { $or: [ {cond1}, {cond2}, ... ] } |
$and | AND - ตรงทุกเงื่อนไข (Explicit) | { $and: [ {cond1}, {cond2} ] } |
$nor | NOR - ไม่ตรงทุกเงื่อนไข | { $nor: [ {cond1}, {cond2} ] } |
$not | NOT - กลับเงื่อนไขเดียว | { field: { $not: { $gt: 10 } } } |
ตัวอย่างเพิ่มเติม
// AND (Implicit - คั่นด้วย Comma)
db.collection.find({ status: "active", age: { $gte: 18 } });
// AND (Explicit - จำเป็นตอนฟิลด์ซ้ำ หรือ Expression ซับซ้อน)
db.collection.find({ $and: [ { status: "active" }, { age: { $gte: 18 } } ] });
// OR
db.collection.find({ $or: [ { status: "active" }, { status: "pending" } ] });
// NOT
db.collection.find({ age: { $not: { $gt: 65 } } }); // age <= 65 หรือ missing
// Combined
db.collection.find({
$and: [
{ $or: [ { type: "A" }, { type: "B" } ] },
{ status: { $ne: "deleted" } },
{ $or: [ { priority: { $gt: 5 } }, { tags: "urgent" } ] }
]
});
⚠️ หมายเหตุ: remove() Deprecated แล้ว
// ใช้แทน
db.multipleConditionDemo.deleteMany({ $or: [ { _id: 2 }, { _id: 3 } ] });