In MongoDB, il $reverseArray l'operatore della pipeline di aggregazione inverte l'ordine degli elementi in una matrice.
Accetta un'espressione di matrice come argomento e restituisce una matrice con gli elementi in ordine inverso.
Esempio
Supponiamo di avere una collezione chiamata products con i seguenti documenti:
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "S", "M", "L" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "XS", "S", "L", "XL" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "M", "L" ] }
Possiamo usare $reverseArray per invertire l'ordine di quegli elementi dell'array.
Esempio:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 1, 2, 3 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) Risultato:
{ "sizes" : [ "S", "M", "L" ], "reversed" : [ "L", "M", "S" ] }
{ "sizes" : [ "XS", "S", "L", "XL" ], "reversed" : [ "XL", "L", "S", "XS" ] }
{ "sizes" : [ "M", "L" ], "reversed" : [ "L", "M" ] } Matrici vuote
Il passaggio di un array vuoto restituisce un array vuoto.
Esempio di documento:
{ "_id" : 4, "prod" : "Zap", "sizes" : [ ] }
Applica $reverseArray :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 4 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) Risultato:
{ "sizes" : [ ], "reversed" : [ ] } Valori Nulli
Passaggio di un valore null restituisce null .
Esempio di documento:
{ "_id" : 5, "prod" : "Tap", "sizes" : null }
Applica $reverseArray :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 5 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) Risultato:
{ "sizes" : null, "reversed" : null } Campi mancanti
Applicazione di $reverseArray in un campo che non esiste nel documento risulta null in fase di restituzione.
Esempio di documento:
{ "_id" : 6, "prod" : "Map" }
Applica $reverseArray :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 6 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) Risultato:
{ "reversed" : null } Tipo di dati errato
Applicazione di $reverseArray in un campo che non si risolve in una matrice genera un errore.
Esempio di documento:
{ "_id" : 7, "prod" : "Box", "sizes" : "XXL" }
Applica $reverseArray :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 7 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) Risultato:
uncaught exception: Error: command failed: {
"ok" : 0,
"errmsg" : "The argument to $reverseArray must be an array, but was of type: string",
"code" : 34435,
"codeName" : "Location34435"
} : 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:639:17
example@sqldat.com/mongo/shell/assert.js:729:16
example@sqldat.com/mongo/shell/db.js:266:5
example@sqldat.com/mongo/shell/collection.js:1058:12
@(shell):1:1