Docs Menu
Docs Home
/
データベース マニュアル
/ / /

$size(集計)

$size

配列内の項目の合計数をカウントして返します。

次の環境でホストされる配置には $size を使用できます。

  • MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです

  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン

$size の構文は次のとおりです。

{ $size: <expression> }

$size の引数は、配列に解決される限り任意のにすることができます。式の詳細については、「式演算子」を参照してください。

$sizeの引数は配列に変換される必要があります。 $sizeの引数が欠落しているか、配列に解決されない場合、 $sizeはエラーになります。

以下のドキュメントを持つinventoryコレクションを検討してください。

db.inventory.insertMany( [
{ _id: 1, item: "ABC1", description: "product 1", colors: [ "blue", "black", "red" ] },
{ _id: 2, item: "ABC2", description: "product 2", colors: [ "purple" ] },
{ _id: 3, item: "XYZ1", description: "product 3", colors: [ ] },
{ _id: 4, item: "ZZZ1", description: "product 4 - missing colors" },
{ _id: 5, item: "ZZZ2", description: "product 5 - colors is string", colors: "blue,red" }
] )

次の集計パイプライン操作では、 $size演算子を使用して、 colors配列内の要素の数を返します。

db.inventory.aggregate([
{
$project: {
item: 1,
numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }
}
}
] )

この操作では、以下を返します。

{ _id: 1, item: "ABC1", numberOfColors: 3 }
{ _id: 2, item: "ABC2", numberOfColors: 1 }
{ _id: 3, item: "XYZ1", numberOfColors: 0 }
{ _id: 4, item: "ZZZ1", numberOfColors: "NA" }
{ _id: 5, item: "ZZZ2", numberOfColors: "NA" }

戻る

$shift

項目一覧