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

Hiển thị danh sách object theo thuộc tính cụ thể với MongoDB

Truy vấn document dựa trên trường lồng trong mảng (dot notation)

Sử dụng dot notation trực tiếp trong find() để lọc document dựa trên thuộc tính của object bên trong mảng.

1. Dữ liệu: Information.Student là mảng object

> db.demo455.insertOne({ Information: { Student: [{ Name: "Chris", Age: 22 }] } });
> db.demo455.insertOne({ Information: { Student: [{ Name: "David", Age: 21 }] } });
> db.demo455.insertOne({ Information: { Student: [{ Name: "Bob", Age: 24 }] } });
> db.demo455.insertOne({ Information: { Student: [{ Name: "Robert", Age: 21 }] } });

2. Tìm học sinh 21 tuổi

> db.demo455.find({ "Information.Student.Age": 21 });

3. Kết quả

{ "_id": ObjectId("5e7e1883dbcb9adb296c95c6"), "Information": { "Student": [{ "Name": "David", "Age": 21 }] } }
{ "_id": ObjectId("5e7e18bcdbcb9adb296c95c8"), "Information": { "Student": [{ "Name": "Robert", "Age": 21 }] } }

Cơ chế hoạt động

  • "Information.Student.Age" duyệt qua từng phần tử của mảng Student
  • Nếu bất kỳ phần tử nào có Age == 21 → document khớp
  • Trả về toàn bộ document gốc (kể cả các phần tử khác trong mảng)

So sánh với $elemMatch

// Tương đương khi chỉ có 1 điều kiện
db.demo455.find({ "Information.Student.Age": 21 });
db.demo455.find({ "Information.Student": { $elemMatch: { Age: 21 } } });

// KHÁC NHAU khi có NHIỀU điều kiện trên CÙNG 1 phần tử
// Ví dụ: Tìm student Age=21 VÀ Name="David"
db.demo455.find({ "Information.Student": { $elemMatch: { Age: 21, Name: "David" } } }); // ĐÚNG
db.demo455.find({ "Information.Student.Age": 21, "Information.Student.Name": "David" }); // SAI - có thể khớp 2 phần tử khác nhau

Tạo index cho truy vấn dot notation

db.demo455.createIndex({ "Information.Student.Age": 1 });

MongoDB tự động tạo Multikey Index cho trường trong mảng.