MongoDBでは、$toUpper 集計パイプライン演算子は、文字列を大文字に変換して結果を返します。
例
petsというコレクションがあるとします。 次のドキュメントを使用:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 }
$toUpperを使用できます これらのフィールドを大文字の文字列に変換して結果を返す演算子。
nameを返す例を次に示します。 およびtype 大文字のフィールド:
db.pets.aggregate(
[
{
$project:
{
name: { $toUpper: "$name" },
type: { $toUpper: "$type" },
weight: "$weight"
}
}
]
) 結果:
{ "_id" : 1, "name" : "WAG", "type" : "DOG", "weight" : 20 }
{ "_id" : 2, "name" : "BARK", "type" : "DOG", "weight" : 10 }
{ "_id" : 3, "name" : "MEOW", "type" : "CAT", "weight" : 7 } 非文字列の変換
$toUpperを使用できます 必ずしも文字列ではない値。引数は、文字列に解決される限り、任意の式にすることができます。
たとえば、$toUpperを使用できます weightを変換するには フィールドには数字しか含まれていませんが、フィールドを大文字の文字列に変更します。
例:
db.pets.aggregate(
[
{
$project:
{
name: { $toUpper: "$name" },
type: { $toUpper: "$type" },
weight: { $toUpper: "$weight" }
}
}
]
) 結果:
{ "_id" : 1, "name" : "WAG", "type" : "DOG", "weight" : "20" }
{ "_id" : 2, "name" : "BARK", "type" : "DOG", "weight" : "10" }
{ "_id" : 3, "name" : "MEOW", "type" : "CAT", "weight" : "7" }
weight フィールドは引用符で囲まれているため、文字列に変換されました。ただし、このフィールドには数字のみが含まれているため、大文字の効果はありません。数字には大文字と小文字がないため、大文字と小文字の違いはわかりません。
数値を文字列に変換したいだけの場合は、$toStringを使用できます。 演算子または$convert オペレーター。