MongoDB 4.4 wprowadził $first operator potoku agregacji.
Ten operator zwraca pierwszy element tablicy.
Przykład
Załóżmy, że mamy kolekcję zwaną graczami z następującymi dokumentami:
{ "_id" : 1, "player" : "Homer", "scores" : [ 1, 5, 3 ] }
{ "_id" : 2, "player" : "Marge", "scores" : [ 8, 17, 18 ] }
{ "_id" : 3, "player" : "Bart", "scores" : [ 15, 11, 8 ] }
Widzimy, że każdy dokument ma scores pole zawierające tablicę.
Możemy użyć $first aby zwrócić pierwszy element każdej z tych tablic.
Przykład:
db.players.aggregate([
{
$project: {
"firstScore": {
$first: "$scores"
}
}
}
]) Wynik:
{ "_id" : 1, "firstScore" : 1 }
{ "_id" : 2, "firstScore" : 8 }
{ "_id" : 3, "firstScore" : 15 } Widzimy, że pierwszy element tablicy został zwrócony dla każdego dokumentu.
Jest to odpowiednik użycia $arrayElemAt operator o wartości zero (0 ):
db.players.aggregate([
{
$project: {
"firstScore": { $arrayElemAt: [ "$scores", 0 ] }
}
}
]) Puste tablice
Jeśli podasz pustą tablicę, $first nie zwróci wartości.
Załóżmy, że wstawiamy do naszej kolekcji następujący dokument:
{ "_id" : 4, "player" : "Farnsworth", "scores" : [ ] } Uruchommy kod ponownie:
db.players.aggregate([
{
$project: {
"firstScore": {
$first: "$scores"
}
}
}
]) Wynik:
{ "_id" : 1, "firstScore" : 1 }
{ "_id" : 2, "firstScore" : 8 }
{ "_id" : 3, "firstScore" : 15 }
{ "_id" : 4 } W tym przypadku dokument 4 nie zwrócił żadnej wartości tablicy. W rzeczywistości nie zwrócił nawet nazwy pola.
Wartości puste i brakujące
Jeśli operand jest pusty lub go brakuje, $first zwraca null .
Załóżmy, że wstawiamy następujący dokument:
{ "_id" : 5, "player" : "Meg", "scores" : null } Uruchommy kod ponownie:
db.players.aggregate([
{
$project: {
"firstScore": {
$first: "$scores"
}
}
}
]) Wynik:
{ "_id" : 1, "firstScore" : 1 }
{ "_id" : 2, "firstScore" : 8 }
{ "_id" : 3, "firstScore" : 15 }
{ "_id" : 4 }
{ "_id" : 5, "firstScore" : null }
Tym razem zwrócił pole o wartości null .
Nieprawidłowy argument
Operand dla $first musi rozwiązać do tablicy, null lub brak. Podanie nieprawidłowego operandu skutkuje błędem.
Aby to zademonstrować, spróbujmy użyć $first przeciwko player pole (które nie jest tablicą):
db.players.aggregate([
{
$project: {
"firstPlayer": {
$first: "$player"
}
}
}
]) Wynik:
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
Zgodnie z oczekiwaniami, zwrócił błąd.