Set Which Fields Are Returned设置返回的字段

If the query bar displays the Project option, you can specify which fields to return in the resulting data. 如果查询栏显示“项目”选项,则可以指定要在结果数据中返回的字段。By default, all fields are returned.默认情况下,将返回所有字段。

To set a projection:要设置投影,请执行以下操作:

  1. In the Query Bar, click Options.在查询栏中,单击“选项”。
  2. Enter the projection document into the Project field.在“项目”字段中输入投影文档。

    To include fields:要包括字段,请执行以下操作:

    Specify the field name and set to 1 in the project document.在项目文档中指定字段名并设置为1

    Example
    { year: 1, name: 1 }

    Only the fields specified in the project document are returned. 仅返回项目文档中指定的字段。The _id field is returned unless it is set to 0 in the Project document.除非在项目文档中将_id字段设置为0,否则将返回该字段。

    To exclude fields:要排除字段,请执行以下操作:

    Specify the field name and set to 0 in the project document.在项目文档中指定字段名并设置为0

    Example
    { year: 0, name: 0 }

    All fields except for the fields specified in the project document are returned.将返回除项目文档中指定的字段之外的所有字段。

    As you type, the Find button is disabled and the Project label turns red until a valid query is entered.键入时,“查找”按钮将被禁用,项目标签将变为红色,直到输入有效的查询。

  3. Click Find to run the query and view the updated results.单击“查找”以运行查询并查看更新的结果。

    Note

    For query result sets larger than 1000 documents, Compass shows a sampling of the results. 对于大于1000个文档的查询结果集,Compass显示结果的采样。 Otherwise, Compass shows the entire result set.否则,Compass将显示整个结果集。

    For details on sampling, see Sampling.有关采样的详细信息,请参阅采样

To learn how project works, see the project entry in the MongoDB Manual.要了解投影如何工作,请参阅MongoDB手册中的project条目。

$project corresponds to choosing specific fields to return in a SQL SELECT statement.$project对应于选择要在SQL SELECT语句中返回的特定字段。

Example

You have 3,235 articles. You would like to see only the headlines and authors of those articles.你有3235篇文章。您只希望看到这些文章的标题和作者。

SQL
SELECT headline, author FROM article;
MongoDB Aggregation
db.article.aggregate(
  { $project : { headline : 1, author : 1 } }
);
Compass Project Option
{ headline : 1, author : 1 }