$ifNull - Amazon DocumentDB

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

$ifNull

如果输入表达式的计算结果为空或未定义,则该$ifNull运算符用于返回指定值。在您想要提供默认值或处理 null/undefined 案例的情况下,此运算符可能很有用。

参数

  • expression:要计算的表达式。

  • replacement:如果<expression>计算结果为 null 或未定义,则返回的值。

示例(MongoDB 外壳)

以下示例演示了当name字段为空或未定义时如何使用$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()