Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

ใช้งาน Not Like ใน MongoDB ด้วย $not และ Regex

MongoDB ไม่มีโอเปอเรเตอร์ NOT LIKE โดยตรง แต่สามารถทำได้ด้วย $not ร่วมกับ Regular Expression

ตัวอย่างการใช้งาน

สร้างคอลเลกชัน notLikeOperatorDemo:

> db.notLikeOperatorDemo.insertOne({"StudentName":"John Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a29c393b406bd3df60dfc") }
> db.notLikeOperatorDemo.insertOne({"StudentName":"John Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a29cc93b406bd3df60dfd") }
> db.notLikeOperatorDemo.insertOne({"StudentName":"John Taylor"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a29df93b406bd3df60dfe") }
> db.notLikeOperatorDemo.insertOne({"StudentName":"Carol Taylor"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a2a1693b406bd3df60dff") }
> db.notLikeOperatorDemo.insertOne({"StudentName":"David Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8a2a2693b406bd3df60e00") }

แสดงข้อมูล:

> db.notLikeOperatorDemo.find().pretty();
{"_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{"_id" : ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName" : "John Smith" }
{"_id" : ObjectId("5c8a29df93b406bd3df60dfe"), "StudentName" : "John Taylor" }
{"_id" : ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName" : "Carol Taylor" }
{"_id" : ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName" : "David Miller" }

ค้นหาเอกสารที่ **ไม่** มีชื่อขึ้นต้นด้วย "John Taylor":

> db.notLikeOperatorDemo.find( { StudentName: { $not: /^John Taylor.*/ } } );
{"_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{"_id" : ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName" : "John Smith" }
{"_id" : ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName" : "Carol Taylor" }
{"_id" : ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName" : "David Miller" }

รูปแบบอื่นที่ใช้ได้: {$not: /John Taylor/} (ค้นหาไม่มีสตริง "John Taylor" อยู่ที่ไหนก็ตามในฟิลด์)