기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$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()