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

Truy vấn chỉ một trường (Single Field Projection) trong MongoDB

Projection trong find() cho phép chỉ định trường cần trả về (include) hoặc loại trừ (exclude). Để lấy một trường đơn lẻ, set trường đó = 1, các trường khác = 0 (trừ _id mặc định 1, set 0 để ẩn).

Dữ liệu mẫu

> db.demo10.insertOne({"StudentId":101,"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0f68a7d7df943a7cec4f9b") }
> db.demo10.insertOne({"StudentId":102,"StudentName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0f68afd7df943a7cec4f9c") }
> db.demo10.insertOne({"StudentId":103,"StudentName":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0f68b5d7df943a7cec4f9d") }

Xem dữ liệu

> db.demo10.find();
{ "_id" : ObjectId("5e0f68a7d7df943a7cec4f9b"), "StudentId" : 101, "StudentName" : "Chris" }
{ "_id" : ObjectId("5e0f68afd7df943a7cec4f9c"), "StudentId" : 102, "StudentName" : "David" }
{ "_id" : ObjectId("5e0f68b5d7df943a7cec4f9d"), "StudentId" : 103, "StudentName" : "Bob" }

Projection: Chỉ lấy StudentName, ẩn _id và StudentId

> db.demo10.find({},{ "_id":0, "StudentId":0 });

Kết quả

{ "StudentName" : "Chris" }
{ "StudentName" : "David" }
{ "StudentName" : "Bob" }

Quy tắc: Không thể trộn include (1) và exclude (0) trừ _id. Ví dụ trên dùng exclude. Cách include: { "StudentName": 1, "_id": 0 }. Projection giảm băng thông mạng và bộ nhớ client, quan trọng cho collection lớn.