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

Truy cập dữ liệu lồng sâu và hiển thị tài liệu cụ thể trong MongoDB

Truy cập subdata (dữ liệu lồng) trong MongoDB

Sử dụng dot notation trong find() để truy vấn các trường lồng sâu nhiều cấp độ.

1. Tạo collection với cấu trúc lồng 3 cấp

> db.demo450.insertOne({
    "Information": {
        "StudentDetails": { "StudentName": "Chris", "StudentAge": 21 }
    }
});
{ "acknowledged": true, "insertedId": ObjectId("5e7b590e71f552a0ebb0a6e6") }

> db.demo450.insertOne({
    "Information": {
        "StudentDetails": { "StudentName": "David", "StudentAge": 23 }
    }
});
{ "acknowledged": true, "insertedId": ObjectId("5e7b591a71f552a0ebb0a6e7") }

> db.demo450.insertOne({
    "Information": {
        "StudentDetails": { "StudentName": "Mike", "StudentAge": 22 }
    }
});
{ "acknowledged": true, "insertedId": ObjectId("5e7b592271f552a0ebb0a6e8") }

2. Xem tất cả

> db.demo450.find();

3. Truy vấn tìm học sinh tên "David"

> db.demo450.find({ "Information.StudentDetails.StudentName": "David" });

4. Kết quả

{ 
    "_id": ObjectId("5e7b591a71f552a0ebb0a6e7"),
    "Information": {
        "StudentDetails": { "StudentName": "David", "StudentAge": 23 }
    }
}

Mẹo hay

  • Dot notation hoạt động với mọi độ sâu lồng nhau
  • Có thể kết hợp với các toán tử so sánh: $gt, $lt, $in, $regex...
  • Ví dụ: { "Information.StudentDetails.StudentAge": { $gte: 22 } }
  • Tạo index trên trường lồng: db.demo450.createIndex({ "Information.StudentDetails.StudentName": 1 })