本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$type
$type聚合运算符返回指定字段的 BSON 数据类型。这对于在聚合操作期间识别字段值的数据类型非常有用。
参数
示例(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()