Di MongoDB, $reverseArray
operator pipa agregasi membalikkan urutan item dalam array.
Ia menerima ekspresi array sebagai argumen dan mengembalikan array dengan elemen dalam urutan terbalik.
Contoh
Misalkan kita memiliki koleksi yang disebut products
dengan dokumen sebagai berikut:
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "S", "M", "L" ] } { "_id" : 2, "prod" : "Hat", "sizes" : [ "XS", "S", "L", "XL" ] } { "_id" : 3, "prod" : "Cap", "sizes" : [ "M", "L" ] }
Kita dapat menggunakan $reverseArray
operator untuk membalik urutan elemen array tersebut.
Contoh:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 1, 2, 3 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Hasil:
{ "sizes" : [ "S", "M", "L" ], "reversed" : [ "L", "M", "S" ] } { "sizes" : [ "XS", "S", "L", "XL" ], "reversed" : [ "XL", "L", "S", "XS" ] } { "sizes" : [ "M", "L" ], "reversed" : [ "L", "M" ] }
Array Kosong
Melewati array kosong akan mengembalikan array kosong.
Contoh dokumen:
{ "_id" : 4, "prod" : "Zap", "sizes" : [ ] }
Terapkan $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 4 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Hasil:
{ "sizes" : [ ], "reversed" : [ ] }
Nilai Null
Melewati nilai null
mengembalikan null
.
Contoh dokumen:
{ "_id" : 5, "prod" : "Tap", "sizes" : null }
Terapkan $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 5 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Hasil:
{ "sizes" : null, "reversed" : null }
Bidang Tidak Ada
Menerapkan $reverseArray
ke bidang yang tidak ada di dokumen menghasilkan null
dikembalikan.
Contoh dokumen:
{ "_id" : 6, "prod" : "Map" }
Terapkan $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 6 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Hasil:
{ "reversed" : null }
Jenis Data Salah
Menerapkan $reverseArray
ke bidang yang tidak diselesaikan ke larik menghasilkan kesalahan.
Contoh dokumen:
{ "_id" : 7, "prod" : "Box", "sizes" : "XXL" }
Terapkan $reverseArray
:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 7 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
)
Hasil:
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 : [email protected]/mongo/shell/utils.js:25:13 [email protected]/mongo/shell/assert.js:18:14 [email protected]/mongo/shell/assert.js:639:17 [email protected]/mongo/shell/assert.js:729:16 [email protected]/mongo/shell/db.js:266:5 [email protected]/mongo/shell/collection.js:1058:12 @(shell):1:1