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

Truy cập sub-document trong truy vấn MongoDB

Để truy cập trường trong sub-document (tài liệu con), sử dụng find() với **dot notation** (ký pháp dấu chấm). Tạo collection:

> db.demo670.insertOne({
  id: 101,
  "details": {
    Name: "Chris", Age: 21, CountryName: "US", SubjectName: "MongoDB"
  }
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3e31d04263e90dac943de") }
> db.demo670.insertOne({
  id: 102,
  "details": { Name: "David", Age: 22, CountryName: "UK", SubjectName: "MySQL" }
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3e33604263e90dac943df") }

Hiển thị dữ liệu:

> db.demo670.find();

Kết quả:

Tìm tài liệu có details.SubjectName = "MongoDB", projection chỉ lấy details.CountryName:

> db.demo670.find({"details.SubjectName":"MongoDB"},{"details.CountryName":1});

Kết quả:

Dot notation rules:

  • "details.SubjectName" - truy cập trường SubjectName bên trong object details
  • "details.CountryName" - projection chỉ lấy CountryName trong details
  • Áp dụng cho cả query filter và projection

Mảng sub-document: Nếu details là mảng [{...}, {...}], dùng "details.SubjectName" vẫn hoạt động (khớp bất kỳ phần tử nào). Dùng $elemMatch khi cần khớp **nhiều trường trên CÙNG MỘT** phần tử mảng.