Để chiếu các trường cụ thể từ một tài liệu bên trong một mảng, bạn có thể sử dụng toán tử vị trí ($).
Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
> db.projectSpecificFieldDemo.insertOne(
... {
... "UniqueId": 101,
... "StudentDetails" : [{"StudentName" : "Chris", "StudentCountryName ": "US"},
... {"StudentName" : "Robert", "StudentCountryName" : "UK"},
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2")
}
> db.projectSpecificFieldDemo.insertOne( { "UniqueId": 102, "StudentDetails" :
[{"StudentName" : "Robert", "StudentCountryName ": "UK"}, {"StudentName" : "David",
"StudentCountryName" : "AUS"}, ] } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca27b106304881c5ce84ba3")
} Sau đây là truy vấn để 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.projectSpecificFieldDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
"UniqueId" : 101,
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentCountryName " : "US"
},
{
"StudentName" : "Robert",
"StudentCountryName" : "UK"
}
]
}
{
"_id" : ObjectId("5ca27b106304881c5ce84ba3"),
"UniqueId" : 102,
"StudentDetails" : [
{
"StudentName" : "Robert",
"StudentCountryName " : "UK"
},
{
"StudentName" : "David",
"StudentCountryName" : "AUS"
}
]
} Sau đây là truy vấn để chiếu các trường cụ thể từ một tài liệu bên trong một mảng
> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty(); Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentCountryName " : "US"
}
]
}