$type - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$type

$type算符用于检查文档中字段的数据类型。它可以在需要特定于类型的操作或验证时使用。运$type算符返回已计算表达式的 BSON 类型。返回的类型是一个字符串,它对应于字段或表达式的类型。

Planner 版本 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字段类型为 “数字”、email字段类型为 “字符串”、name字段类型为 “字符串” 的文档。

代码示例

要查看使用该$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()