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

Loại bỏ tất cả trường trừ một trường trong tài liệu lồng nhau qua projection MongoDB

Để loại bỏ các trường không mong muốn, đặt giá trị là 0 trong projection. Các trường còn lại sẽ được hiển thị.

Tạo collection với tài liệu lồng nhau:

> db.demo237.insertOne({
...   _id:101,
...   Product: {
...     description1: {id:1001 },
...     description2: {Name:"Product-1" },
...     description3: {Price:550 }
...   }
...});
{ "acknowledged" : true, "insertedId" : 101 }

Hiển thị đầy đủ:

> db.demo237.find().pretty();
{ "_id" : 101, "Product" : {
  "description1" : { "id" : 1001 },
  "description2" : { "Name" : "Product-1" },
  "description3" : { "Price" : 550 }
} }

Projection loại bỏ description1 và description3, chỉ giữ description2:

> db.demo237.find({}, { "Product.description1": 0, "Product.description3": 0 });

Kết quả chỉ còn description2:

{ "_id" : 101, "Product" : { "description2" : { "Name" : "Product-1" } } }