기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$ifNull
입력 표현식이 null 또는 정의되지 않은 것으로 평가되는 경우 연$ifNull산자를 사용하여 지정된 값을 반환합니다. 이 연산자는 기본값을 제공하거나 null/미정의 사례를 처리하려는 시나리오에서 유용할 수 있습니다.
파라미터
예제(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()