MongoDBでは、$trim 集計パイプライン演算子は、文字列の最初と最後から空白を削除します。これにはヌル文字が含まれます。
指定した文字を削除することもできます。たとえば、これを使用してすべてのハイフン文字を削除できます(- )またはピリオド(. )またはすべてのs 文字など
例
petsというコレクションがあるとします。 次のドキュメントで:
{ "_id" : 1, "name" : "Wagg", "type" : " Dog ", "weight" : 20 }
type フィールドには、Dogという単語の両側に空白が含まれます 。 $trimを使用できます 空白を削除してそのフィールドを返す演算子。
例:
db.pets.aggregate([
{
$project: {
name: 1,
type: { $trim: { input: "$type" } }
}
}
]) 結果:
{ "_id" : 1, "name" : "Wagg", "type" : "Dog" }
予想通り、type フィールドは空白なしで返されました。
$ltrimを使用することもできます 文字列の左側をトリミングする演算子と$rtrim 文字列の右側をトリミングする演算子。
実際、MongoDBが空白文字と見なす文字はかなりあります。完全なリストについては、MongoDBの空白文字を参照してください。
他のキャラクターをトリミングする
$trim 演算子はcharsを受け入れます トリミングする文字を指定できるパラメータ。
例:
db.pets.aggregate([
{
$project: {
name: { $trim: { input: "$name", chars: "g" } }
}
}
]) 結果:
{ "_id" : 1, "name" : "Wa" }
両方のgを削除しました 単語の末尾からの文字。
複数の文字をトリミングする
charsにすべて含めることで、複数の文字をトリミングできます。 引数。
例:
db.pets.aggregate([
{
$project: {
name: { $trim: { input: "$name", chars: "Wgz" } }
}
}
]) 結果:
{ "_id" : 1, "name" : "a" }
この場合、charsとして3文字を指定しました 引数、およびそれらの文字の2つがたまたま文字列の両端にありました。したがって、これらの2つの文字はトリミングされました。実際には、トリミングされた3文字–1つのW および2つのg 文字。
ただし、これを行うときは注意してください。 zを置き換えるとどうなりますか aを使用 charsで 引数:
db.pets.aggregate([
{
$project: {
name: { $trim: { input: "$name", chars: "Wga" } }
}
}
]) 結果:
{ "_id" : 1, "name" : "" }
文字列全体が消えました。 Wだけでなくトリミングされています およびg 文字列の両端からですが、aもトリミングされています 弦から–弦の真ん中にあったとしても。
数値のトリミング
$trim 演算子は文字列を処理します。 weightをトリミングしようとすると フィールドでは、エラーが発生します。これは、weightが原因です フィールドは数値であり、文字列ではありません。
db.pets.aggregate([
{
$project: {
name: 1,
weight: { $trim: { input: "$weight", chars: "0" } }
}
}
]) 結果:
Error: command failed: {
"ok" : 0,
"errmsg" : "$trim requires its input to be a string, got 20 (of type double) instead.",
"code" : 50699,
"codeName" : "Location50699"
} : aggregate failed :
example@sqldat.com/mongo/shell/utils.js:25:13
example@sqldat.com/mongo/shell/assert.js:18:14
example@sqldat.com/mongo/shell/assert.js:618:17
example@sqldat.com/mongo/shell/assert.js:708:16
example@sqldat.com/mongo/shell/db.js:266:5
example@sqldat.com/mongo/shell/collection.js:1046:12
@(shell):1:1
このエラーは、$trimにもかかわらず、doubleを提供したことを示しています。 演算子では、入力が文字列である必要があります。
本当にゼロを削除したい場合は、最初にそれを文字列に変換する必要があります。 $convertのいずれかでそれを行うことができます または$toString オペレーター。
例:
db.pets.aggregate([
{
$project: {
name: 1,
weight: { $trim: { input: { $toString: "$weight" }, chars: "0" } }
}
}
]) 結果:
{ "_id" : 1, "name" : "Wagg", "weight" : "2" }
$convertを使用すると、doubleに戻すことができます。 または$toDouble オペレーター。
完全な例:
db.pets.aggregate([
{
$project: {
name: 1,
weight: { $toDouble: { $trim: { input: { $toString: "$weight" }, chars: "0" } } }
}
}
]) 結果:
{ "_id" : 1, "name" : "Wagg", "weight" : 2 }