本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$
$投影运算符将数组字段的内容限制为仅返回与查询条件匹配的第一个元素。它用于投影单个匹配的数组元素。
参数
示例(MongoDB 外壳)
以下示例演示了使用$投影运算符仅返回匹配的数组元素。
创建示例文档
db.students.insertMany([
{ _id: 1, name: "Alice", grades: [85, 92, 78, 95] },
{ _id: 2, name: "Bob", grades: [70, 88, 92, 65] },
{ _id: 3, name: "Charlie", grades: [95, 89, 91, 88] }
]);
查询示例
db.students.find(
{ grades: { $gte: 90 } },
{ name: 1, "grades.$": 1 }
);
输出
{ "_id" : 1, "name" : "Alice", "grades" : [ 92 ] }
{ "_id" : 2, "name" : "Bob", "grades" : [ 92 ] }
{ "_id" : 3, "name" : "Charlie", "grades" : [ 95 ] }
在此示例中,仅返回每个学生大于或等于 90 的一年级成绩。
代码示例
要查看使用$投影运算符的代码示例,请选择要使用的语言的选项卡:
- 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.find(
{ grades: { $gte: 90 } },
{ projection: { name: 1, "grades.$": 1 } }
).toArray();
console.log(JSON.stringify(result, null, 2));
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.find(
{'grades': {'$gte': 90}},
{'name': 1, 'grades.$': 1}
))
print(result)
client.close()
example()