Để tìm kiếm giá trị trong document lồng nhau, sử dụng $match trong pipeline aggregate() kết hợp $unwind để phân rã mảng.
Tạo collection thông tin sinh viên lồng nhau
> db.demo648.insertOne({
StudentInformation: [
{ Name: "John", CountryName: "US" },
{ Name: "David", CountryName: "AUS" },
{ Name: "Chris", CountryName: "US" },
{ Name: "Robert", CountryName: "UK" }
]
});
Hiển thị document gốc
> db.demo648.find();
Kết quả (1 document chứa mảng 4 sinh viên):
{
"StudentInformation": [
{ "Name": "John", "CountryName": "US" },
{ "Name": "David", "CountryName": "AUS" },
{ "Name": "Chris", "CountryName": "US" },
{ "Name": "Robert", "CountryName": "UK" }
]
}
Aggregate tìm sinh viên ở US
> db.demo648.aggregate([
{ $unwind: "$StudentInformation" },
{ $match: { "StudentInformation.CountryName": "US" } },
{ $project: { _id: 0 } }
])
Kết quả (2 sinh viên ở US):
{
"StudentInformation": { "Name": "John", "CountryName": "US" }
}
{
"StudentInformation": { "Name": "Chris", "CountryName": "US" }
}
Giải thích quy trình:
$unwind: "$StudentInformation": Phân rã mảng → 4 document riêng biệt, mỗi document chứa 1 sinh viên$match: Lọc giữ document cóCountryName = "US"$project: {_id: 0}: Ẩn _id, chỉ hiển thị object StudentInformation
Ứng dụng thực tế: Tìm đơn hàng chứa sản phẩm cụ thể, tìm user có role xác định trong mảng roles, lọc log event theo loại...
Lưu ý: Nếu mảng lớn, $unwind tạo ra nhiều document trung gian → tiêu tốn bộ nhớ. Xem xét $filter (MongoDB 3.2+) để lọc trong mảng không cần unwind.