MongoDBでは、$reverseArray 集計パイプライン演算子は、配列内のアイテムの順序を逆にします。
引数として配列式を受け入れ、要素を逆の順序で含む配列を返します。
例
productsというコレクションがあるとします。 次のドキュメントを使用:
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "S", "M", "L" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "XS", "S", "L", "XL" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "M", "L" ] }
$reverseArrayを使用できます これらの配列要素の順序を逆にする演算子。
例:
db.products.aggregate(
[
{ $match: { _id: { $in: [ 1, 2, 3 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) 結果:
{ "sizes" : [ "S", "M", "L" ], "reversed" : [ "L", "M", "S" ] }
{ "sizes" : [ "XS", "S", "L", "XL" ], "reversed" : [ "XL", "L", "S", "XS" ] }
{ "sizes" : [ "M", "L" ], "reversed" : [ "L", "M" ] } 空のアレイ
空の配列を渡すと、空の配列が返されます。
サンプルドキュメント:
{ "_id" : 4, "prod" : "Zap", "sizes" : [ ] }
$reverseArrayを適用します :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 4 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) 結果:
{ "sizes" : [ ], "reversed" : [ ] } ヌル値
nullの値を渡す nullを返します 。
サンプルドキュメント:
{ "_id" : 5, "prod" : "Tap", "sizes" : null }
$reverseArrayを適用します :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 5 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) 結果:
{ "sizes" : null, "reversed" : null } 欠落しているフィールド
$reverseArrayを適用する ドキュメントに存在しないフィールドに移動すると、nullになります 返送されます。
サンプルドキュメント:
{ "_id" : 6, "prod" : "Map" }
$reverseArrayを適用します :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 6 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) 結果:
{ "reversed" : null } 間違ったデータ型
$reverseArrayを適用する 配列に解決されないフィールドに移動すると、エラーが発生します。
サンプルドキュメント:
{ "_id" : 7, "prod" : "Box", "sizes" : "XXL" }
$reverseArrayを適用します :
db.products.aggregate(
[
{ $match: { _id: { $in: [ 7 ] } } },
{
$project:
{
_id: 0,
sizes: 1,
reversed: { $reverseArray: [ "$sizes" ] }
}
}
]
) 結果:
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