$size - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$size

$size クエリ演算子は、配列フィールドの要素数が正確に指定された数であるドキュメントに一致します。これは、配列の長さに基づいてドキュメントをフィルタリングするのに役立ちます。

パラメータ

  • field: 確認する配列フィールド。

  • count: 配列に含める必要がある要素の正確な数。

例 (MongoDB シェル)

次の例は、 $size演算子を使用して、厳密に 3 つのタグを持つすべての製品を検索する方法を示しています。

サンプルドキュメントを作成する

db.products.insertMany([ { _id: 1, name: "Laptop", tags: ["electronics", "computers", "portable"] }, { _id: 2, name: "Mouse", tags: ["electronics", "accessories"] }, { _id: 3, name: "Desk", tags: ["furniture", "office", "workspace"] }, { _id: 4, name: "Monitor", tags: ["electronics"] } ]);

クエリの例

db.products.find({ tags: { $size: 3 } });

出力

{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] } { "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }

コードの例

$size クエリ演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('products'); const result = await collection.find({ tags: { $size: 3 } }).toArray(); console.log(JSON.stringify(result, null, 2)); await client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['products'] result = list(collection.find({'tags': {'$size': 3}})) print(result) client.close() example()