MongoDB4.4は$lastを導入しました 集約パイプライン演算子。
この演算子は、配列の最後の要素を返します。
例
次のドキュメントを持つplayersというコレクションがあるとします。
{ "_id" : 1, "player" : "Homer", "scores" : [ 1, 5, 3 ] }
{ "_id" : 2, "player" : "Marge", "scores" : [ 8, 17, 18 ] }
{ "_id" : 3, "player" : "Bart", "scores" : [ 15, 11, 8 ] }
各ドキュメントにscoresがあることがわかります 配列を含むフィールド。
$lastを使用できます これらの各配列の最後の要素を返します。
例:
db.players.aggregate([
{
$project: {
"lastScore": {
$last: "$scores"
}
}
}
]) 結果:
{ "_id" : 1, "lastScore" : 3 }
{ "_id" : 2, "lastScore" : 18 }
{ "_id" : 3, "lastScore" : 8 } 配列の最後の要素が各ドキュメントに対して返されていることがわかります。
これは、$arrayElemAtを使用するのと同じです。 -1の値を持つ演算子 :
db.players.aggregate([
{
$project: {
"firstScore": { $arrayElemAt: [ "$scores", -1 ] }
}
}
]) 空のアレイ
空の配列を指定した場合、$last 値を返しません。
次のドキュメントをコレクションに挿入するとします。
{ "_id" : 4, "player" : "Farnsworth", "scores" : [ ] } コードをもう一度実行してみましょう:
db.players.aggregate([
{
$project: {
"lastScore": {
$last: "$scores"
}
}
}
]) 結果:
{ "_id" : 1, "lastScore" : 3 }
{ "_id" : 2, "lastScore" : 18 }
{ "_id" : 3, "lastScore" : 8 }
{ "_id" : 4 } この場合、ドキュメント4は配列の値を返しませんでした。フィールド名も返されませんでした。
ヌル値と欠落値
オペランドがnullまたは欠落している場合は、$last nullを返します 。
次のドキュメントを挿入するとします。
{ "_id" : 5, "player" : "Meg", "scores" : null } コードをもう一度実行してみましょう:
db.players.aggregate([
{
$project: {
"lastScore": {
$last: "$scores"
}
}
}
]) 結果:
{ "_id" : 1, "lastScore" : 3 }
{ "_id" : 2, "lastScore" : 18 }
{ "_id" : 3, "lastScore" : 8 }
{ "_id" : 4 }
{ "_id" : 5, "lastScore" : null }
今回は、値がnullのフィールドを返しました。 。
無効なオペランド
$lastのオペランド 配列、null、または欠落に解決する必要があります。無効なオペランドを指定すると、エラーが発生します。
これを実証するために、$lastを使用してみましょう playerに対して フィールド(配列ではありません):
db.players.aggregate([
{
$project: {
"lastPlayer": {
$last: "$player"
}
}
}
]) 結果:
Error: command failed: {
"ok" : 0,
"errmsg" : "$last's argument must be an array, but is string",
"code" : 28689,
"codeName" : "Location28689"
} : 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
予想どおり、エラーが返されました。