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

Tìm phần tử cụ thể trong tài liệu nhúng (embedded document) MongoDB

Sử dụng $unwind, $match, $project

Quy trình: bẻ mảng ($unwind), lọc phần tử thỏa điều kiện ($match), chọn trường cần hiển thị ($project).

Dữ liệu mẫu

> db.demo744.insertOne({
  studentInformation: [
    { studentName: "Robert", grade: "A" },
    { studentName: "Bob", grade: "C" },
    { studentName: "John", grade: "B" },
    { studentName: "Sam", grade: "A" }
  ]
});

Truy vấn: tìm học sinh grade "A"

db.demo744.aggregate([
  { $unwind: "$studentInformation" },
  { $match: { "studentInformation.grade": "A" } },
  { $project: { "studentInformation.studentName": 1 } }
]);

Kết quả

{ "_id": ObjectId("..."), "studentInformation": { "studentName": "Robert" } }
{ "_id": ObjectId("..."), "studentInformation": { "studentName": "Sam" } }

Trả về tên các học sinh đạt grade A.