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

Truy vấn mảng MongoDB để lấy giá trị cụ thể

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

Quy trình chuẩn: bẻ mảng, lọc giá trị mong muốn, chọn trường hiển thị.

Dữ liệu mẫu

> db.demo761.insertMany([
  { details: [{ student: { FullName: "Chris Brown" } }] },
  { details: [{ student: { FullName: "Chris Taylor" } }] }
]);

Truy vấn: tìm FullName = "Chris Taylor"

db.demo761.aggregate([
  { $unwind: "$details" },
  { $match: { "details.student.FullName": "Chris Taylor" } },
  { $project: { "details.student.FullName": 1, _id: 0 } }
]);

Kết quả

{ "details": { "student": { "FullName": "Chris Taylor" } } }

Chỉ trả về trường FullName của bản ghi khớp.