ใน MongoDB เทียบเท่ากับคำสั่ง SQL WHERE IN(1,2,...) คือการใช้ตัวดำเนินการ $in ไวยากรณ์มีดังนี้:
db.yourCollectionName.find({yourFieldName:{$in:[yourValue1,yourValue2,....N]}}).pretty();
ตัวอย่างการใช้งาน
สร้างคอลเลกชันพร้อมเอกสารตัวอย่าง:
> db.whereInDemo.insertOne({"StudentName":"John","StudentMathScore":57});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca281ec6304881c5ce84ba5") }
> db.whereInDemo.insertOne({"StudentName":"Larry","StudentMathScore":89});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca281f56304881c5ce84ba6") }
> db.whereInDemo.insertOne({"StudentName":"Chris","StudentMathScore":98});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca281fd6304881c5ce84ba7") }
> db.whereInDemo.insertOne({"StudentName":"Robert","StudentMathScore":99});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca2820a6304881c5ce84ba8") }
> db.whereInDemo.insertOne({"StudentName":"Bob","StudentMathScore":97});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca282206304881c5ce84ba9") }
แสดงเอกสารทั้งหมดด้วย find():
> db.whereInDemo.find().pretty();
ผลลัพธ์:
{ "_id" : ObjectId("5ca281ec6304881c5ce84ba5"), "StudentName" : "John", "StudentMathScore" : 57 }
{ "_id" : ObjectId("5ca281f56304881c5ce84ba6"), "StudentName" : "Larry", "StudentMathScore" : 89 }
{ "_id" : ObjectId("5ca281fd6304881c5ce84ba7"), "StudentName" : "Chris", "StudentMathScore" : 98 }
{ "_id" : ObjectId("5ca2820a6304881c5ce84ba8"), "StudentName" : "Robert", "StudentMathScore" : 99 }
{ "_id" : ObjectId("5ca282206304881c5ce84ba9"), "StudentName" : "Bob", "StudentMathScore" : 97 }
คำสั่งเทียบเท่า WHERE IN ด้วย $in:
> db.whereInDemo.find({StudentMathScore:{$in:[97,98,99]}}).pretty();
ผลลัพธ์ (เฉพาะนักเรียนที่ได้คะแนน 97, 98, 99):
{ "_id" : ObjectId("5ca281fd6304881c5ce84ba7"), "StudentName" : "Chris", "StudentMathScore" : 98 }
{ "_id" : ObjectId("5ca2820a6304881c5ce84ba8"), "StudentName" : "Robert", "StudentMathScore" : 99 }
{ "_id" : ObjectId("5ca282206304881c5ce84ba9"), "StudentName" : "Bob", "StudentMathScore" : 97 }