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

Truy cập giá trị mảng trong MongoDB với dot notation

Truy vấn phần tử mảng object bằng dấu chấm

Khi mảng chứa object, dùng dot notation tênMảng.trường để truy vấn document chứa phần tử khớp.

Dữ liệu sản phẩm

> db.demo326.insertOne({
    id: 101,
    "ProductDetails": [
        {"ProductId": "Prod-101", "ProductName": "Product-1"},
        {"ProductId": "Prod-102", "ProductName": "Product-2"}
    ]
});
> db.demo326.insertOne({
    id: 103,
    "ProductDetails": [
        {"ProductId": "Prod-104", "ProductName": "Product-5"},
        {"ProductId": "Prod-105", "ProductName": "Product-6"}
    ]
});

Tìm document có ProductId = "Prod-104"

> db.demo326.find({ "ProductDetails.ProductId": "Prod-104" });

Kết quả

{
    "_id": ObjectId("..."),
    "id": 103,
    "ProductDetails": [
        {"ProductId": "Prod-104", "ProductName": "Product-5"},
        {"ProductId": "Prod-105", "ProductName": "Product-6"}
    ]
}

Lưu ý: Truy vấn này trả về toàn bộ document (kể cả các phần tử khác trong mảng). Để chỉ lấy phần tử khớp, dùng $elemMatch trong projection hoặc $filter trong aggregation.