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

Projection chỉ một cột trong MongoDB

Projection trong find() cho phép chọn trường cần trả về: 1 (include) hoặc 0 (exclude). _id mặc định include, phải tắt rõ ràng.

Dữ liệu mẫu

> db.demo216.insertOne({"ClientName":"John","ClientAge":34});
> db.demo216.insertOne({"ClientName":"Bob","ClientAge":32});
> db.demo216.insertOne({"ClientName":"Mike","ClientAge":35});

Truy vấn chỉ lấy ClientName

> db.demo216.find({}, {_id:0, "ClientAge":0});

Kết quả

{ "ClientName" : "John" }
{ "ClientName" : "Bob" }
{ "ClientName" : "Mike" }

Quy tắc projection:

  • Không thể mix include (1) và exclude (0) trừ _id
  • {_id:0, ClientName:1} ✓ (include mode + tắt _id)
  • {_id:0, ClientAge:0} ✓ (exclude mode + tắt _id) - ví dụ này
  • {ClientName:1, ClientAge:0} ✗ Lỗi: mix mode

Ứng dụng: Giảm bandwidth, tăng tốc độ truy vấn, che dữ liệu nhạy cảm. Dùng trong find, findOne, aggregate $project.