Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách chiếu các trường cụ thể từ document bên trong mảng trong MongoDB?

Để chiếu (project) các trường cụ thể từ một document bên trong mảng, bạn có thể sử dụng toán tử vị trí ($) trong MongoDB.

Tạo dữ liệu mẫ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") }

Hiển thị tất cả document:

> db.projectSpecificFieldDemo.find().pretty();

Kết quả:

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

Chiếu trường cụ thể từ mảng

Sử dụng toán tử vị trí $ để chỉ chiếu element đầu tiên khớp với điều kiện truy vấn:

> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();

Kết quả chỉ trả về element khớp trong mảng:

{ "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"), "StudentDetails" : [ 
    { "StudentName" : "Chris", "StudentCountryName " : "US" } 
  ] }

Lưu ý: Toán tử $ chỉ chiếu element đầu tiên khớp với điều kiện truy vấn trong mảng. Nếu cần chiếu nhiều element hoặc tất cả element khớp, hãy sử dụng $elemMatch trong projection hoặc aggregation pipeline.