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

Lọc trường trong đối tượng và lấy giá trị SubjectName cụ thể trong MongoDB

Để lọc và lấy trường cụ thể, sử dụng projection kết hợp $filter và $match trong aggregation. Tạo collection:

> db.demo507.insertOne({
  "Information": [
    {"Name":"John","SubjectName":"MySQL"},
    {"Name":"Bob","SubjectName":"MongoDB"},
    {"Name":"Chris","SubjectName":"MySQL"},
    {"Name":"David","SubjectName":"C++"}
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8836d3987b6e0e9d18f577") }

Hiển thị dữ liệu gốc:

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

Kết quả:

Pipeline aggregation: $match lọc tài liệu có SubjectName="MySQL", sau đó $project với $filter chỉ giữ các phần tử có SubjectName="MySQL", cuối cùng projection chỉ lấy trường SubjectName:

> db.demo507.aggregate([
  {$match: {"Information.SubjectName" : "MySQL" } },
  {$project: {
    _id:0,
    Information: {
      $filter: {
        input: '$Information',
        as: 'result',
        cond: {$eq: ['$$result.SubjectName', 'MySQL']}
      }
    }
  }},
  {$project: {Information: { SubjectName:1}}}
]);

Kết quả chỉ chứa các môn học MySQL:

Giải thích: $match giảm tài liệu đầu vào, $filter lọc mảng con, $project cuối cùng chỉ chọn trường cần thiết.