ในการเข้าถึงข้อมูลย่อย คุณต้องใช้คีย์ใน MongoDB ให้เราสร้างคอลเลกชันพร้อมเอกสาร -
>db.demo450.insertOne({"Information":{"StudentDetails":{"StudentName":"Chris","StudentAge":21}}}); {
"acknowledged" : true,
"insertedId" : ObjectId("5e7b590e71f552a0ebb0a6e6")
}
>db.demo450.insertOne({"Information":{"StudentDetails":{"StudentName":"David","StudentAge":23}}});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b591a71f552a0ebb0a6e7")
}
>db.demo450.insertOne({"Information":{"StudentDetails":{"StudentName":"Mike","StudentAge":22}}});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b592271f552a0ebb0a6e8")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo450.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e7b590e71f552a0ebb0a6e6"), "Information" : { "StudentDetails" : {
"StudentName" : "Chris", "StudentAge" : 21 } } }
{ "_id" : ObjectId("5e7b591a71f552a0ebb0a6e7"), "Information" : { "StudentDetails" : {
"StudentName" : "David", "StudentAge" : 23 } } }
{ "_id" : ObjectId("5e7b592271f552a0ebb0a6e8"), "Information" : { "StudentDetails" : {
"StudentName" : "Mike", "StudentAge" : 22 } } } ต่อไปนี้เป็นแบบสอบถามเพื่อเข้าถึงข้อมูลย่อยใน MongoDB -
> db.demo450.find({"Information.StudentDetails.StudentName":"David"}); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e7b591a71f552a0ebb0a6e7"), "Information" : { "StudentDetails" : {
"StudentName" : "David", "StudentAge" : 23 } } }