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

Lấy giá trị lồng sâu trong JSON MongoDB với dot notation

Dot notation trong projection của find() cho phép trích xuất trường lồng sâu trong object/array mà không cần aggregate.

Dữ liệu mẫu phức tạp

> db.demo235.insertOne({
    "id":101, 
    "details":[ 
        { "Name":"Chris Brown", "Age":21 }, 
        { "Name":"David Miller", "Age":24 } 
    ], 
    "otherdetails":[ 
        { "Score":56, "Subject":"MongoDB" }, 
        { "Score":78, "Subject":"MySQL" } 
    ] 
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e418d22f4cebbeaebec514b") }

Truy vấn projection dot notation

> db.demo235.find({}, {"otherdetails.Subject":1, _id:0});

Kết quả

{ "otherdetails" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }

Giải thích:

  • {"otherdetails.Subject":1}: Chỉ lấy trường Subject từ mỗi object trong mảng otherdetails
  • Giữ cấu trúc mảng, chỉ lọc trường con
  • _id:0: Tắt _id

So sánh:

Phương phápĐộ phức tạpLinh hoạtHiệu suất
find() + dot notationThấpTrung bìnhCao (dùng index)
aggregate $projectTrung bìnhCaoCao
aggregate $map/$filterCaoRất caoTrung bình

Chọn cách đơn giản nhất đáp ứng nhu cầu.