Để trả về các trường cụ thể, hãy sử dụng dự án $ tổng hợp. 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.returnSpecificFieldDemo.insertOne(
{
"StudentId":1,
"StudentDetails": [
{
"StudentName":"Larry",
"StudentAge":21,
"StudentCountryName":"US"
},
{
"StudentName":"Chris",
"StudentAge":23,
"StudentCountryName":"AUS"
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce23d3236e8b255a5eee943")
} 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.returnSpecificFieldDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5ce23d3236e8b255a5eee943"),
"StudentId" : 1,
"StudentDetails" : [
{
"StudentName" : "Larry",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 23,
"StudentCountryName" : "AUS"
}
]
} Sau đây là truy vấn để trả về các trường cụ thể từ một mảng -
> db.returnSpecificFieldDemo.aggregate([{$project:{_id:0, StudentId:'$StudentId', StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName',1] }}}]); Điều này sẽ tạo ra kết quả sau -
{ "StudentId" : 1, "StudentCountryName" : "AUS" }