定義
互換性
次の環境でホストされる配置には $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" }