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

Truy cập giá trị subdocument khi khóa là số trong MongoDB

Khi khóa của subdocument là số (lưu dưới dạng string), dùng ký pháp ngoặc vuông ["key"].

Tạo collection

> db.accessSubDocumentDemo.insertOne({
    "Details": {
        "1": { "StudentLowerScore": "33", "StudentHoghScore": "55" },
        "2": { "StudentLowerScore": "45", "StudentHoghScore": "65" },
        "3": { "StudentLowerScore": "39", "StudentHoghScore": "91" },
        "4": { "StudentLowerScore": "41", "StudentHoghScore": "85" }
    }
});
{ "acknowledged": true, "insertedId": ObjectId("5cd3baf0edc6604c74817cd6") }

Hiển thị tài liệu

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

Truy cập subdocument với khóa "1" (số nhưng lưu là string)

> db.accessSubDocumentDemo.findOne().Details["1"];

Kết quả:

{ "StudentLowerScore": "33", "StudentHoghScore": "55" }

Giải thích: Trong MongoDB, tên trường (key) luôn là string. Dù nhập như số 1, nó được lưu là "1". Truy cập bằng Details["1"] hoặc Details.1 (nhưng Details.1 có thể gây nhầm lẫn với chỉ số mảng). An toàn nhất dùng Details["1"].