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

Chỉ hiển thị một trường đơn lẻ từ tất cả tài liệu MongoDB

Sử dụng projection** (chiếu) trong find() để chỉ trả về trường mong muốn. Đặt trường = 1 để hiển thị, = 0 để ẩn. _id mặc định = 1, phải tắt rõ ràng.

Tạo collection:

> db.demo384.insertOne({"StudentName":"Chris Brown","StudentCountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5b67a022064be7ab44e7f2") }
> db.demo384.insertOne({"StudentName":"David Miller","StudentCountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5b67ab22064be7ab44e7f3") }
> db.demo384.insertOne({"StudentName":"John Doe","StudentCountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5b67b422064be7ab44e7f4") }

Xem đầy đủ:

> db.demo384.find();

Chỉ lấy StudentCountryName (ẩn _id và StudentName):

> db.demo384.find({},{_id:0,StudentName:0});

Kết quả:

Quy tắc projection:

  • Không thể 섞 include (1) và exclude (0) trừ _id
  • {field: 1} → chỉ lấy field đó (+ _id)
  • {field: 0, _id: 0} → lấy tất cả trừ field và _id
  • Projection lồng nhau: {"details.name": 1}

Giảm băng thông mạng và bộ nhớ client khi chỉ cần một số trường.