A mapping (projection) declaration is used to restrict the return fields of all query-matching documents. Projection lists the fields in the result set that you want to include or exclude in the form of a document. You can specify the fields to include (for example, {field:1}) or specify the fields to exclude (for example, {field:0}). The default _id is included in the result collection, and to exclude _id fields from the result set, you need to specify the Exclude _id field ({_id:0}) in projection. In addition to the _id field, the inclusion and exclusion semantics cannot be used in a projection.
returns all fields that match a document:
If you do not specify the Projection,find () method, all fields that match the document are returned.
Copy Code code as follows:
Db.inventory.find ({type: ' food '})
This example returns all documents with the value "food" for the Type field in the inventory collection, and the returned document contains all the fields.
returns the specified field and _id field:
A projection can specify more than one field explicitly. In the following operation, the Find () method returns all the documents that match. In the result set, only the Item and Qty fields, and the default _id fields are returned.
Copy Code code as follows:
Db.inventory.find ({type: ' food '}, {item:1, qty:1})
returns only the specified fields:
You can remove it from the result by specifying the Exclude _id field in projection, as shown in the following example:
Copy Code code as follows:
Db.inventory.find ({type: ' food '}, {item:1, qty:1, _id:0})
returns a field other than excluding:
You can use a projection to exclude one or a set of fields, as follows:
Copy Code code as follows:
Db.inventory.find ({type: ' food '}, {type:0})
This action returns all documents with the Type field value food, and the Type field does not return in the result.
projection of array fields:
The $elemMatch and $slice operators are the only way to projection an array.