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