$type - Amazon DocumentDB

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

$type

$type 集計演算子は、指定されたフィールドの BSON データ型を返します。これは、集計オペレーション中にフィールド値のデータ型を識別するのに役立ちます。

パラメータ

  • expression: 返される型を持つフィールドまたは式。

例 (MongoDB シェル)

次の例は、 $type演算子を使用して、各製品の料金フィールドのデータ型を識別する方法を示しています。

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

db.inventory.insertMany([ { _id: 1, item: "Notebook", price: 15.99 }, { _id: 2, item: "Pen", price: "2.50" }, { _id: 3, item: "Eraser", price: 1 }, { _id: 4, item: "Ruler", price: null } ]);

クエリの例

db.inventory.aggregate([ { $project: { item: 1, price: 1, priceType: { $type: "$price" } } } ]);

出力

[ { _id: 1, item: 'Notebook', price: 15.99, priceType: 'double' }, { _id: 2, item: 'Pen', price: '2.50', priceType: 'string' }, { _id: 3, item: 'Eraser', price: 1, priceType: 'int' }, { _id: 4, item: 'Ruler', price: null, priceType: 'null' } ]

コードの例

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

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('inventory'); const result = await collection.aggregate([ { $project: { item: 1, price: 1, priceType: { $type: "$price" } } } ]).toArray(); console.log(result); 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['inventory'] result = list(collection.aggregate([ { '$project': { 'item': 1, 'price': 1, 'priceType': { '$type': '$price' } } } ])) print(result) client.close() example()