Docs Home / Compass / Interact with Your Data / Query

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 subset of the results. Otherwise, Compass shows the entire result set.对于大于1000个文档的查询结果集,Compass会显示结果的一个子集。否则,Compass将显示整个结果集。

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

How Does the Compass Query Compare to MongoDB and SQL Queries?Compass查询与MongoDB和SQL查询相比如何?

$project corresponds to choosing specific fields to return in a SQL SELECT statement.对应于在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 AggregationMongoDB聚合
db.article.aggregate(
{ $project : { headline : 1, author : 1 } }
);
Compass Project OptionCompass投影选项
{ headline : 1, author : 1 }

Learn More了解更多

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