本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$type
$type 彙總運算子會傳回指定欄位的 BSON 資料類型。這有助於識別彙總操作期間欄位值的資料類型。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $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()