$type - Amazon DocumentDB

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

$type

$type 演算子は、ドキュメント内のフィールドのデータ型をチェックするために使用されます。タイプ固有のオペレーションまたは検証が必要な場合に使用できます。$type 演算子は、評価された式の BSON タイプを返します。返される型は、フィールドまたは式の型に対応する文字列です。

プランナーバージョン 2.0 で のインデックスサポートが追加されました$type

パラメータ

  • expression : 評価する式。

例 (MongoDB シェル)

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

db.documents.insertMany([ { _id: 1, name: "John", age: 30, email: "john@example.com" }, { _id: 2, name: "Jane", age: "25", email: 123456 }, { _id: 3, name: 123, age: true, email: null } ]);

クエリの例

db.documents.find({ $or: [ { age: { $type: "number" } }, { email: { $type: "string" } }, { name: { $type: "string" } } ] })

出力

[ { "_id": 1, "name": "John", "age": 30, "email": "john@example.com" }, { "_id": 2, "name": "Jane", "age": "25", "email": 123456 } ]

このクエリは、 ageフィールドが「number」型、 emailフィールドが「string」型、 nameフィールドが「string」型であるドキュメントを返します。

コードの例

$type コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function findByType() { 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('documents'); const results = await collection.find({ $or: [ { age: { $type: 'number' } }, { email: { $type: 'string' } }, { name: { $type: 'string' } } ] }).toArray(); console.log(results); client.close(); } findByType();
Python
from pymongo import MongoClient def find_by_type(): 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['documents'] results = list(collection.find({ '$or': [ {'age': {'$type': 'number'}}, {'email': {'$type': 'string'}}, {'name': {'$type': 'string'}} ] })) print(results) client.close() find_by_type()