คุณสามารถใช้ตัวดำเนินการ $in เพื่อค้นหารายการอาร์เรย์หลายรายการ เพื่อให้เข้าใจแนวคิด ให้เราสร้างคอลเลกชันพร้อมกับเอกสาร
แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -
>db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith",
"StudentCoreSubject":["Compiler","Operating System","Computer Networks"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7ef07b559dd2396bcfbfc4")
}
>db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor",
"StudentCoreSubject":["MongoDB","MySQL","SQL Server"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7ef09d559dd2396bcfbfc5")
}
>db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"Bob","StudentLastName":"Taylor",
"StudentCoreSubject":["MongoDB","MySQL","SQL Server"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7ef0c7559dd2396bcfbfc6")
}
>db.findByMultipleArrayDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Johnson",
"StudentCoreSubject":["Compiler","Operating System","Computer Networks"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7ef0f2559dd2396bcfbfc7")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้ −
> db.findByMultipleArrayDemo.find().pretty();
ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c7ef07b559dd2396bcfbfc4"),
"StudentFirstName" : "John",
"StudentLastName" : "Smith",
"StudentCoreSubject" : [
"Compiler",
"Operating System",
"Computer Networks"
]
}
{
"_id" : ObjectId("5c7ef09d559dd2396bcfbfc5"),
"StudentFirstName" : "Carol",
"StudentLastName" : "Taylor",
"StudentCoreSubject" : [
"MongoDB",
"MySQL",
"SQL Server"
]
}
{
"_id" : ObjectId("5c7ef0c7559dd2396bcfbfc6"),
"StudentFirstName" : "Bob",
"StudentLastName" : "Taylor",
"StudentCoreSubject" : [
"MongoDB",
"MySQL",
"SQL Server"
]
}
{
"_id" : ObjectId("5c7ef0f2559dd2396bcfbfc7"),
"StudentFirstName" : "David",
"StudentLastName" : "Johnson",
"StudentCoreSubject" : [
"Compiler",
"Operating System",
"Computer Networks"
]
} ใช้ตัวดำเนินการ $in เพื่อค้นหาโดยหลายรายการอาร์เรย์ -
> db.findByMultipleArrayDemo.find({ StudentCoreSubject: { $in: ["Compiler", "Computer Networks"] }}).pretty(); ต่อไปนี้เป็นผลลัพธ์ -
{
"_id" : ObjectId("5c7ef07b559dd2396bcfbfc4"),
"StudentFirstName" : "John",
"StudentLastName" : "Smith",
"StudentCoreSubject" : [
"Compiler",
"Operating System",
"Computer Networks"
]
}
{
"_id" : ObjectId("5c7ef0f2559dd2396bcfbfc7"),
"StudentFirstName" : "David",
"StudentLastName" : "Johnson",
"StudentCoreSubject" : [
"Compiler",
"Operating System",
"Computer Networks"
]
}