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

Dự án trường mảng cụ thể trong bộ sưu tập MongoDB?

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.projectionAnElementDemo.insertOne(
...    {
...       "CustomerId":100,
...       "CustomerDetails": [
...          {
...             "CustomerName": "Chris",
...             "CustomerCountryName": "US"
...          },
...          {
...             "CustomerName": "Robert",
...             "CustomerCountryName": "UK"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd31c56b64f4b851c3a13ea")
}

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.projectionAnElementDemo.find().pretty();

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

{
   "_id" : ObjectId("5cd31c56b64f4b851c3a13ea"),
   "CustomerId" : 100,
   "CustomerDetails" : [
      {
         "CustomerName" : "Chris",
         "CustomerCountryName" : "US"
      },
      {
         "CustomerName" : "Robert",
         "CustomerCountryName" : "UK"
      }
   ]
}

Sau đây là truy vấn tới phần tử dự án trong trường mảng -

> db.projectionAnElementDemo.find({},{CustomerId:1, "CustomerDetails.CustomerName":1}).pretty();

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

{
   "_id" : ObjectId("5cd31c56b64f4b851c3a13ea"),
   "CustomerId" : 100,
   "CustomerDetails" : [
      {
         "CustomerName" : "Chris"
      },
      {
         "CustomerName" : "Robert"
      }
   ]
}