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

Cách dùng find() tìm kiếm khóa lồng nhau (nested keys) trong MongoDB

Giới thiệu

Để tìm kiếm trên các trường lồng nhau (nested fields) trong MongoDB, bạn sử dụng **dot notation** (ký pháp dấu chấm) trong query filter: "cha.con".

Cú pháp

db.collection.find({ "truongNgoai.truongTrong": giaTri });

Ví dụ minh họa

1. Tạo collection với nested object

> db.timKhoaNested.insertOne({
    "TenKhachHang": "Larry",
    "TuoiKhachHang": 28,
    "ThongTinThem": { "DaCoHocVan": true, "QuocGia": "US" }
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca20e8b66324ffac2a7dc64") }

> db.timKhoaNested.insertOne({
    "TenKhachHang": "Chris",
    "TuoiKhachHang": 29,
    "ThongTinThem": { "DaCoHocVan": false, "QuocGia": "UK" }
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca20ea366324ffac2a7dc65") }

> db.timKhoaNested.insertOne({
    "TenKhachHang": "David",
    "TuoiKhachHang": 39,
    "ThongTinThem": { "DaCoHocVan": true, "QuocGia": "AUS" }
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca20eba66324ffac2a7dc66") }

2. Tìm khách hàng có QuocGia = "UK" trong nested object

> db.timKhoaNested.find({ "ThongTinThem.QuocGia": "UK" }).pretty();

3. Kết quả

{ "_id" : ObjectId("5ca20ea366324ffac2a7dc65"), "TenKhachHang" : "Chris", "TuoiKhachHang" : 29, "ThongTinThem" : { "DaCoHocVan" : false, "QuocGia" : "UK" } }

Các trường hợp dot notation

Cấu trúc documentQueryÝ nghĩa
{ a: { b: { c: 1 } } }{ "a.b.c": 1 }3 cấp lồng nhau
{ arr: [ { x: 1 }, { x: 2 } ] }{ "arr.x": 1 }BẤT KỲ element nào có x=1
{ arr: [ { x: 1 }, { x: 2 } ] }{ "arr.0.x": 1 }Element index 0 có x=1
{ a: { b: [1,2,3] } }{ "a.b": 2 }Mảng con chứa giá trị 2

Kết hợp với các toán tử khác

// So sánh
db.collection.find({ "user.profile.age": { $gte: 18 } });

// Regex
db.collection.find({ "user.profile.name": { $regex: "^John" } });

// $in
db.collection.find({ "user.address.city": { $in: ["Hanoi", "HCMC"] } });

// $exists
db.collection.find({ "user.profile.phone": { $exists: true } });

Index trên nested field

// Single field index
db.collection.createIndex({ "ThongTinThem.QuocGia": 1 });

// Compound index
db.collection.createIndex({ "ThongTinThem.QuocGia": 1, "ThongTinThem.DaCoHocVan": -1 });

Lưu ý

  • Dot notation **bắt buộc trong ngoặc kép**: "outer.inner"
  • Khác với JavaScript object access: doc.outer.inner (không ngoặc)
  • Hoạt động với find, update, aggregation ($match, $project, $group...)
  • Index trên nested field hoạt động như bình thường (multikey nếu là array)