MongoDBでは、$size 集計パイプライン演算子は、配列内のアイテムの総数をカウントして返します。
$size 演算子は1つの引数を受け入れます。引数は、配列に解決される任意の有効な式にすることができます。
例
testというコレクションがあるとします。 次のドキュメントを使用:
{ "_id" : 1, "data" : [ ] }
{ "_id" : 2, "data" : [ "a" ] }
{ "_id" : 3, "data" : [ "a", "b" ] }
{ "_id" : 4, "data" : [ "a", "b", "c" ] }
{ "_id" : 5, "data" : [ 1, 1, 1, 1 ] }
$sizeを使用できます それぞれのdataの配列内のアイテムの数を返します フィールド。
db.test.aggregate(
[
{ $match: { _id: { $in: [ 1, 2, 3, 4, 5 ] } } },
{
$project:
{
_id: 0,
data: 1,
result: { $size: [ "$data" ] }
}
}
]
) 結果:
{ "data" : [ ], "result" : 0 }
{ "data" : [ "a" ], "result" : 1 }
{ "data" : [ "a", "b" ], "result" : 2 }
{ "data" : [ "a", "b", "c" ], "result" : 3 }
{ "data" : [ 1, 1, 1, 1 ], "result" : 4 } ネストされた配列
$size 演算子はネストされた配列に降りて、それらの要素をカウントしません。配列をトップレベルから評価します。
コレクションに次のドキュメントがあるとします。
{ "data" : [ [ 1, 2 ], 3 ], "result" : 2 }
そして、$sizeを適用します それに:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 6 ] } } },
{
$project:
{
_id: 0,
data: 1,
result: { $size: [ "$data" ] }
}
}
]
) 結果:
{ "data" : [ [ 1, 2 ], 3 ], "result" : 2 } ネストされた配列は、(含まれている要素の数に関係なく)1つの要素としてカウントされます。
間違ったデータ型
引数は、配列に解決される限り、任意の有効な式にすることができます。配列に解決されない場合は、エラーが発生します。
次のドキュメントがあるとします。
{ "_id" : 7, "data" : 3 }
data フィールドは配列に解決されません。
$sizeを適用すると次のようになります その分野へ:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 7 ] } } },
{
$project:
{
_id: 0,
data: 1,
result: { $size: [ "$data" ] }
}
}
]
) 結果:
Error: command failed: {
"ok" : 0,
"errmsg" : "The argument to $size must be an array, but was of type: double",
"code" : 17124,
"codeName" : "Location17124"
} : 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
エラーメッセージは、The argument to $size must be an array, but was of type: doubleであることを示しています。 。
欠落しているフィールド
フィールドがドキュメントに存在しない場合、エラーが返されます。
次のドキュメントがあるとします。
{ "_id" : 8 }
そして、$sizeを適用します そのドキュメントへ:
db.test.aggregate(
[
{ $match: { _id: { $in: [ 8 ] } } },
{
$project:
{
_id: 0,
data: 1,
result: { $size: [ "$data" ] }
}
}
]
) 結果:
Error: command failed: {
"ok" : 0,
"errmsg" : "The argument to $size must be an array, but was of type: missing",
"code" : 17124,
"codeName" : "Location17124"
} : aggregate failed :
example@sqldat.com/mongo/shell/utils.js:25:13
example@sqldat.com/mongo/shell/assert.js:18:14
_asseexample@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