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

Truy vấn theo trường con (sub-field) trong MongoDB với Dot Notation

MongoDB sử dụng Dot Notation (ký hiệu dấu chấm) để truy cập và truy vấn các trường bên trong embedded document (sub-document).

Cú pháp

db.collection.find({ "trườngCha.trườngCon": "giáTrị" })

Ví dụ minh họa

Tạo collection queryBySubFieldDemo với embedded document StudentPersonalDetails và StudentScores:

> db.queryBySubFieldDemo.insertOne({
    "StudentPersonalDetails": { "StudentName": "John", "StudentHobby": "Photography" },
    "StudentScores": { "MathScore": 56 }
});
> db.queryBySubFieldDemo.insertOne({
    "StudentPersonalDetails": { "StudentName": "Chris", "StudentHobby": "Reading" },
    "StudentScores": { "MathScore": 97 }
});

Hiển thị tất cả:

> db.queryBySubFieldDemo.find().pretty();

Kết quả:

{
    "_id" : ObjectId("..."),
    "StudentPersonalDetails" : { "StudentName" : "John", "StudentHobby" : "Photography" },
    "StudentScores" : { "MathScore" : 56 }
}
{
    "_id" : ObjectId("..."),
    "StudentPersonalDetails" : { "StudentName" : "Chris", "StudentHobby" : "Reading" },
    "StudentScores" : { "MathScore" : 97 }
}

Truy vấn sub-field: Tìm sinh viên tên "Chris"

> db.queryBySubFieldDemo.find({ "StudentPersonalDetails.StudentName": "Chris" }).pretty();

Kết quả:

{
    "_id" : ObjectId("..."),
    "StudentPersonalDetails" : { "StudentName" : "Chris", "StudentHobby" : "Reading" },
    "StudentScores" : { "MathScore" : 97 }
}

Các trường hợp mở rộng

  • Truy vấn nhiều cấp: { "a.b.c.d": "value" }
  • Kết hợp điều kiện: { "StudentPersonalDetails.StudentName": "Chris", "StudentScores.MathScore": { $gt: 90 } }
  • Projection (chỉ lấy field con): db.coll.find({}, { "StudentPersonalDetails.StudentName": 1, _id: 0 })
  • Update sub-field: db.coll.updateOne({...}, { $set: { "StudentScores.MathScore": 100 } })

Lưu ý về Index

Để tối ưu truy vấn sub-field, hãy tạo index trên đường dẫn dot notation:

db.queryBySubFieldDemo.createIndex({ "StudentPersonalDetails.StudentName": 1 });

Index này gọi là single field index trên embedded field.