翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$cond
Amazon DocumentDB の $cond演算子は、条件式を評価し、2 つの可能な結果式のいずれかを返すために使用されます。
パラメータ
例 (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()