本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$type
$type 運算子用於檢查文件中欄位的資料類型。它可以在需要特定類型操作或驗證時使用。$type 運算子會傳回評估表達式的 BSON 類型。傳回的類型是字串,對應至欄位或表達式的類型。
規劃器 2.0 版已新增 的索引支援。 $type
參數
範例 (MongoDB Shell)
建立範例文件
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()