翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$
$ 射影演算子は、配列フィールドの内容を制限して、クエリ条件に一致する最初の要素のみを返します。これは、単一の一致する配列要素を射影するために使用されます。
パラメータ
例 (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()