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

Chiếu (project) trường mảng cụ thể trong collection MongoDB

Tạo collection:

> db.projectionAnElementDemo.insertOne({
    "CustomerId": 100,
    "CustomerDetails": [
        {"CustomerName": "Chris", "CustomerCountryName": "US"},
        {"CustomerName": "Robert", "CustomerCountryName": "UK"}
    ]
});
{ "acknowledged": true, "insertedId": ObjectId("5cd31c56b64f4b851c3a13ea") }

Hiển thị tất cả

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

Chiếu chỉ CustomerId và CustomerName trong mảng

> db.projectionAnElementDemo.find(
    {},
    { CustomerId: 1, "CustomerDetails.CustomerName": 1 }
).pretty();

Kết quả (chỉ giữ CustomerId và CustomerName, bỏ CustomerCountryName):

{
    "_id": ObjectId("5cd31c56b64f4b851c3a13ea"),
    "CustomerId": 100,
    "CustomerDetails": [
        {"CustomerName": "Chris"},
        {"CustomerName": "Robert"}
    ]
}

Lưu ý: _id mặc định luôn trả về trừ khi loại bỏ rõ ràng (_id: 0). Chiếu mảng chỉ giữ một số trường của mỗi phần tử.