Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để truy cập dữ liệu con trong MongoDB và hiển thị một tài liệu cụ thể?


Để truy cập dữ liệu con, bạn cần sử dụng khóa trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

>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")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.demo450.find();

Điều này sẽ tạo ra kết quả sau -

{ "_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 } } }

Sau đây là truy vấn để truy cập dữ liệu con trong MongoDB -

> db.demo450.find({"Information.StudentDetails.StudentName":"David"});

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5e7b591a71f552a0ebb0a6e7"), "Information" : { "StudentDetails" : {
"StudentName" : "David", "StudentAge" : 23 } } }