หากต้องการค้นหาค่าในอาร์เรย์ภายในช่วง ให้ใช้ $gt และ $lt ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo341.insertOne({
... "Name": "Chris",
... "productDetails" : [
... {
... "ProductPrice" : {
... "Price" : 800
... }
... },
... {
... "ProductPrice" : {
... "Price" : 400
... }
... },
... {
... "ProductPrice" : {
... "Price" : 300
... }
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e53ed5cf8647eb59e5620a7")
}
> db.demo341.insertOne({
... "Name": "Chris",
... "productDetails" : [
... {
... "ProductPrice" : {
... "Price" : 1000
... }
... },
... {
... "ProductPrice" : {
... "Price" : 1200
... }
... },
... {
... "ProductPrice" : {
... "Price" : 1300
... }
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e53edc1f8647eb59e5620a8")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo341.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5e53ed5cf8647eb59e5620a7"), "Name" : "Chris", "productDetails" : [
{ "ProductPrice" : { "Price" : 800 } }, { "ProductPrice" : { "Price" : 400 } },
{ "ProductPrice" : { "Price" : 300 } }
]
}
{
"_id" : ObjectId("5e53edc1f8647eb59e5620a8"), "Name" : "Chris", "productDetails" : [
{ "ProductPrice" : { "Price" : 1000 } }, { "ProductPrice" : { "Price" : 1200 } },
{ "ProductPrice" : { "Price" : 1300 } }
]
} ต่อไปนี้เป็นแบบสอบถามเพื่อค้นหาค่าในอาร์เรย์ที่มีหลายเกณฑ์ -
> db.demo341.aggregate([
... { "$match": {
... "productDetails": {
... "$elemMatch": {
... "ProductPrice.Price": {
... "$gt": 600,
... "$lt": 900
... }
... }
... }
... }}
... ]).pretty(); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5e53ed5cf8647eb59e5620a7"),
"Name" : "Chris",
"productDetails" : [
{
"ProductPrice" : {
"Price" : 800
}
},
{
"ProductPrice" : {
"Price" : 400
}
},
{
"ProductPrice" : {
"Price" : 300
}
}
]
}