คุณสามารถใช้ตัวดำเนินการ $where สำหรับสิ่งนี้ ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a219345990cee87fd88c")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a22a345990cee87fd88d")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a23c345990cee87fd88e")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2a24d345990cee87fd88f")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.searchDocumentArrayIntegerDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5cd2a219345990cee87fd88c"),
"StudentFirstName" : "John",
"StudentScores" : [
45,
78,
89,
90
]
}
{
"_id" : ObjectId("5cd2a22a345990cee87fd88d"),
"StudentFirstName" : "Larry",
"StudentScores" : [
45,
43,
34,
33
]
}
{
"_id" : ObjectId("5cd2a23c345990cee87fd88e"),
"StudentFirstName" : "Chris",
"StudentScores" : [ ]
}
{
"_id" : ObjectId("5cd2a24d345990cee87fd88f"),
"StudentFirstName" : "David",
"StudentScores" : [
99
]
} กรณีที่ 1 − ถามเมื่ออาร์เรย์มีค่าอย่างน้อยหนึ่งค่า -
> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } ); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] }
{ "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] } กรณีที่ 2 − ถามเมื่ออาร์เรย์มีค่าร่วมในเอกสารทั้งหมด −
> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1}); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }