This article mainly introduces the method of the MongoDB query operation to limit the return field, and the friend who needs can refer to the following mapping (projection) declaration to restrict the return fields of all queries matching documents. Projection lists the fields to include or exclude in the result set as documents. You can specify which 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 set, and to exclude the _id field from the result set, the Exclude _id field ({_id:0}) needs to be specified in projection. In addition to the _id field, inclusion and exclusion semantics cannot be combined in a single projection.
returns all fields of the matching document:
If the Projection,find () method is not specified, all fields matching the document are returned.
The code is 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 fields.
returns the specified field and _id field:
A projection can explicitly specify multiple fields. In the following operation, the Find () method returns all documents that match. In the result set, only the Item and Qty fields, the default _id field is also returned.
The code is as follows:
Db.inventory.find ({type: ' food '}, {item:1, qty:1})
only the specified fields are returned:
You can remove it from the results by specifying the Exclude _id field in projection, as shown in the following example:The code is as follows:
Db.inventory.find ({type: ' food '}, {item:1, qty:1, _id:0})
Returns a field other than the exclusion:
You can use a projection to exclude one or a group of fields, as follows:
The code is as follows:
Db.inventory.find ({type: ' food '}, {type:0})
This operation returns all the Type field values for the food document, in the result the Type field does not return.
Projection of array fields:
$elemMatch and $slice operators are the only way to projection an array.
MongoDB query operation limits methods for returning fields