MongoDBでは、$concat 集計パイプライン演算子は、2つ以上の文字列を連結し、連結された文字列を返します。
例
employeesというコレクションがあるとします。 次のドキュメントで:
{
"_id" : 1,
"firstName" : "Sandy",
"surname" : "Beach",
"position" : "Lifesaver",
"salary" : 55000
}
$concatを使用できます 名と名前を連結する演算子:
db.employees.aggregate(
[
{ $project: {
_id: 0,
name: { $concat: [ "$firstName", "$surname" ] }
}
}
]
) 結果:
{ "name" : "SandyBeach" } その他の文字列
前の例では2つの文字列を連結していますが、必要に応じてさらに連結することもできます。
たとえば、名と名前の間にスペースを挿入できます。
例:
db.employees.aggregate(
[
{ $project: {
_id: 0,
name: { $concat: [ "$firstName", " ", "$surname" ] }
}
}
]
) 結果:
{ "name" : "Sandy Beach" } 連結にさらにフィールドを含めることもできます。
例:
db.employees.aggregate(
[
{ $project: {
_id: 0,
employee: {
$concat: [ "$firstName", " ", "$surname", ", ", "$position" ]
}
}
}
]
) 結果:
{ "employee" : "Sandy Beach, Lifesaver" } その他のデータ型
$concat 演算子は文字列のみをサポートします。 $concatを適用する 別のタイプに変更すると、エラーが発生します。
例:
db.employees.aggregate(
[
{ $project: {
_id: 0,
name: {
$concat: [ "$firstName", "$salary" ]
}
}
}
]
) 結果:
Error: command failed: {
"ok" : 0,
"errmsg" : "$concat only supports strings, not double",
"code" : 16702,
"codeName" : "Location16702"
} : 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
この例では、文字列を数値と連結しようとしましたが、 $ concatは文字列のみをサポートし、doubleはサポートしないというエラーが発生しました。 。