$ifNull - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$ifNull

$ifNull 演算子は、入力式が null または未定義と評価された場合に、指定された値を返すために使用されます。この演算子は、デフォルト値を指定したり、null/undefined ケースを処理したりする場合に役立ちます。

パラメータ

  • expression: 評価する式。

  • replacement: が null または未定義と<expression>評価された場合に返される値。

例 (MongoDB シェル)

次の例は、 name フィールドが null または未定義の場合に、 $ifNull演算子を使用してデフォルト値を指定する方法を示しています。

サンプルドキュメントを作成する

db.users.insertMany([ { _id: 1, name: "John" }, { _id: 2, name: null }, { _id: 3 } ]);

クエリの例

db.users.aggregate([ { $project: { _id: 1, name: { $ifNull: ["$name", "No Name"] } } } ]);

出力

[ { "_id": 1, "name": "John" }, { "_id": 2, "name": "No Name" }, { "_id": 3, "name": "No Name" } ]

コードの例

$ifNull コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

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('users'); const pipeline = [ { $project: { _id: 1, name: { $ifNull: ["$name", "No Name"] } } } ]; const cursor = await collection.aggregate(pipeline); await cursor.forEach(doc => { console.log(doc); }); 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.users pipeline = [ { "$project": { "_id": 1, "name": { "$ifNull": ["$name", "No Name"] } } } ] result = collection.aggregate(pipeline) for doc in result: print(doc) client.close() example()