MongoDB 4.4 ha introdotto il $first operatore della pipeline di aggregazione.
Questo operatore restituisce il primo elemento di una matrice.
Esempio
Supponiamo di avere una collezione chiamata giocatori con i seguenti documenti:
{ "_id" : 1, "player" : "Homer", "scores" : [ 1, 5, 3 ] }
{ "_id" : 2, "player" : "Marge", "scores" : [ 8, 17, 18 ] }
{ "_id" : 3, "player" : "Bart", "scores" : [ 15, 11, 8 ] }
Possiamo vedere che ogni documento ha un scores campo che contiene una matrice.
Possiamo usare $first per restituire il primo elemento di ciascuna di queste matrici.
Esempio:
db.players.aggregate([
{
$project: {
"firstScore": {
$first: "$scores"
}
}
}
]) Risultato:
{ "_id" : 1, "firstScore" : 1 }
{ "_id" : 2, "firstScore" : 8 }
{ "_id" : 3, "firstScore" : 15 } Possiamo vedere che il primo elemento dell'array è stato restituito per ogni documento.
Questo equivale all'utilizzo di $arrayElemAt operatore con valore zero (0 ):
db.players.aggregate([
{
$project: {
"firstScore": { $arrayElemAt: [ "$scores", 0 ] }
}
}
]) Matrici vuote
Se fornisci un array vuoto, $first non restituirà un valore.
Supponiamo di inserire il seguente documento nella nostra raccolta:
{ "_id" : 4, "player" : "Farnsworth", "scores" : [ ] } Eseguiamo nuovamente il codice:
db.players.aggregate([
{
$project: {
"firstScore": {
$first: "$scores"
}
}
}
]) Risultato:
{ "_id" : 1, "firstScore" : 1 }
{ "_id" : 2, "firstScore" : 8 }
{ "_id" : 3, "firstScore" : 15 }
{ "_id" : 4 } In questo caso, il documento 4 non ha restituito alcun valore per l'array. In effetti, non ha nemmeno restituito il nome del campo.
Valori nulli e mancanti
Se l'operando è nullo o mancante, $first restituisce null .
Supponiamo di inserire il seguente documento:
{ "_id" : 5, "player" : "Meg", "scores" : null } Eseguiamo nuovamente il codice:
db.players.aggregate([
{
$project: {
"firstScore": {
$first: "$scores"
}
}
}
]) Risultato:
{ "_id" : 1, "firstScore" : 1 }
{ "_id" : 2, "firstScore" : 8 }
{ "_id" : 3, "firstScore" : 15 }
{ "_id" : 4 }
{ "_id" : 5, "firstScore" : null }
Questa volta ha restituito il campo con un valore di null .
Operando non valido
L'operando per $first deve risolversi in una matrice, nulla o mancante. Fornire un operando non valido genera un errore.
Per dimostrarlo, proviamo a utilizzare $first contro il player campo (che non è un array):
db.players.aggregate([
{
$project: {
"firstPlayer": {
$first: "$player"
}
}
}
]) Risultato:
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
Come previsto, ha restituito un errore.