

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1project
<a name="project"></a>

Amazon DocumentDB 中的`$project`运算符允许您有选择地在输出文档中包含或排除字段，将值传递到下一个管道阶段，以及从输入文档值中计算新字段。

**参数**
+ `field`: 要在输出文档中包含或排除的字段，它可以是字段路径（例如，“a.b.c”）。
+ `1`或`true`：在输出中包含该字段。
+ `0`或`false`：从输出中排除该字段。

## 示例（MongoDB 外壳）
<a name="project-examples"></a>

以下示例演示了`$project`运算符在学生集合中的用法

**创建示例文档**

```
db.students.insertMany([
  { "_id": 1, "name": "Alejandro Rosalez", "math": 85, "science": 92, "grade": "A" },
  { "_id": 2, "name": "Carlos Salazar", "math": 78, "science": 84, "grade": "B" },
  { "_id": 3, "name": "Nikhil Jayashankar", "math": 95, "science": 89, "grade": "A" },
  { "_id": 4, "name": "Shirley Rodriguez", "math": 72, "science": 76, "grade": "B" }
  ]);
```

此查询仅在输出中包含`name`和`math`字段。除非明确排除，否则默认情况下会包含该`_id`字段。

```
db.students.aggregate([
  { $project: { "name": 1, "math": 1 } }
])
```

**输出**

```
{ _id: 1, name: "Alejandro Rosalez", math: 85 }
{ _id: 2, name: "Carlos Salazar", math: 78 }
{ _id: 3, name: "Nikhil Jayashankar", math: 95 }
{ _id: 4, name: "Shirley Rodriguez", math: 72 }
```

此查询从输出中排除`grade`和`_id`字段，显示所有其他字段（`name`、`math`、`science`）。

```
db.students.aggregate([
  { $project: { "grade": 0, "_id": 0 } }
])
```

**输出**

```
{ name: "Alejandro Rosalez", math: 85, science: 92 }
{ name: "Carlos Salazar", math: 78, science: 84 }
{ name: "Nikhil Jayashankar", math: 95, science: 89 }
{ name: "Shirley Rodriguez", math: 72, science: 76 }
```

## 代码示例
<a name="project-code"></a>

要查看使用该`$project`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('students');

  const result = await collection.aggregate([
    { $project: { "name": 1, "math": 1 } }
  ]).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['students']

    result = list(collection.aggregate([
        { '$project': { 'name': 1, 'math': 1 } }
    ]))
    print(result)

    client.close()

example()
```

------