기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$cond
Amazon DocumentDB의 $cond 연산자는 조건 표현식을 평가하고 두 개의 가능한 결과 표현식 중 하나를 반환하는 데 사용됩니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 연$cond산자를 사용하여 사람의 연령에 따라 값을 반환하는 방법을 보여줍니다.
샘플 문서 생성
db.people.insertMany([
{ _id: 1, name: "John Doe", age: 35 },
{ _id: 2, name: "Jane Doe", age: 25 },
{ _id: 3, name: "Bob Smith", age: 65 }
]);
쿼리 예제
db.people.aggregate([
{
$project: {
name: 1,
ageGroup: {
$cond: {
if: { $lt: ["$age", 30] },
then: "young",
else: {
$cond: {
if: { $lt: ["$age", 65] },
then: "middle-aged",
else: "elderly"
}
}
}
}
}
}
])
출력
[
{ "_id" : 1, "name" : "John Doe", "ageGroup" : "middle-aged" },
{ "_id" : 2, "name" : "Jane Doe", "ageGroup" : "young" },
{ "_id" : 3, "name" : "Bob Smith", "ageGroup" : "elderly" }
]
코드 예제
$cond 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.
- 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('people');
const result = await collection.aggregate([
{ $project: {
name: 1,
ageGroup: {
$cond: {
if: { $lt: ["$age", 30] },
then: "young",
else: {
$cond: {
if: { $lt: ["$age", 65] },
then: "middle-aged",
else: "elderly"
}
}
}
}
}
}
]).toArray();
console.log(result);
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.people
result = list(collection.aggregate([
{
'$project': {
'name': 1,
'ageGroup': {
'$cond': {
'if': { '$lt': ["$age", 30]},
'then': "young",
'else': {
'$cond': {
'if': { '$lt': ["$age", 65]},
'then': "middle-aged",
'else': "elderly"
}
}
}
}
}
}
]))
print(result)
client.close()
example()