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

Trả về trường cụ thể trong MongoDB?

Để chỉ trả về (project) các trường cụ thể trong MongoDB, bạn sử dụng tham số thứ hai của phương thức find() - projection document.

Tạo dữ liệu mẫu

> db.specificFieldDemo.insertOne({"FirstName":"John","LastName":"Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb8019a623186894665ae31") }
> db.specificFieldDemo.insertOne({"FirstName":"John","LastName":"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb801ab623186894665ae32") }
> db.specificFieldDemo.insertOne({"FirstName":"David","LastName":"Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb801b3623186894665ae33") }
> db.specificFieldDemo.insertOne({"FirstName":"Sam","LastName":"Williams"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb801bf623186894665ae34") }

Hiển thị tất cả:

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

Chỉ trả về trường LastName (loại trừ _id)

> db.specificFieldDemo.find({},{_id:0,LastName:1});

Kết quả:


Quy tắc Projection

  • { trường: 1 } - Bao gồm trường (include)
  • { trường: 0 } - Loại trừ trường (exclude)
  • Không thể 섞 include và exclude (trừ _id)
  • _id luôn được include mặc định, phải đặt _id: 0 để loại trừ

Ví dụ khác: find({}, {FirstName: 1, LastName: 1, _id: 0}) - trả về FirstName và LastName.