The MongoDB query operation limits the method to return the field

  • 2020-05-10 23:06:26
  • OfStack

The mapping (projection) declaration is used to limit the return fields of all queries matching documents. projection documents the fields to be included or excluded from the result set. You can specify fields to include (for example: {field:1}) or fields to exclude (for example: {field: 0}). The default _id is included in the result set. To exclude the _id field from the result set, specify the exclude _id field in projection ({_id:0}). Except for the _id field, inclusion and exclusion semantics cannot be used jointly in an projection.

Returns all fields of the matching document:

If projection is not specified, the find() method returns all fields for all matching documents.
db.inventory.find( { type: 'food' } )

This example returns all documents in the inventory collection whose type field has the value "food", and the returned document contains all the fields.

Returns the specified field and the _id field:

An projection can explicitly specify multiple fields. In the following operation, the find() method returns all matched documents. In the result set, only the item and qty fields are returned, and the default _id field is also returned.
db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )


Only returns the specified field:
You can remove the _id field from the result by specifying exclude _id in projection, as shown in the following example:
db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )


Returns fields other than those excluded:
You can use 1 projection to exclude 1 or 1 set of fields, as follows:
db.inventory.find( { type: 'food' }, { type:0 } )

This operation returns all documents with the type field value of food, and the type field does not return in the result.

Array field projection:
The   $elemMatch and $slice operators are the only way to projection an array.

Related articles: