문서 메뉴
문서 홈
/
MongoDB 매뉴얼
/ / /

$toString(집계)

이 페이지의 내용

  • 정의
  • 행동
  • 예제
$toString

값을 문자열로 변환합니다. 값을 문자열로 변환할 수 없는 경우 $toString 오류가 발생합니다. 값이 null이거나 누락된 경우 $toString 은 null을 반환합니다.

$toString 의 구문은 다음과 같습니다:

{
$toString: <expression>
}

$toString 는 유효한 표현식을 사용합니다.

$toString는 다음 $convert 표현식의 약칭입니다.

{ $convert: { input: <expression>, to: "string" } }

다음도 참조하세요.

다음 표에는 문자열로 변환할 수 있는 입력 유형이 나열되어 있습니다.

입력 유형
행동
부울
부울 값을 문자열로 반환합니다.
더블
이중 값을 문자열로 반환합니다.
10진수
십진수 값을 문자열로 반환합니다.
Integer
정수 값을 문자열로 반환합니다.
Long
긴 값을 문자열로 반환합니다.
ObjectId
객체 ID 값을 16진수 문자열로 반환합니다 ...
문자열
아니요. 문자열 값을 반환합니다.
날짜
날짜를 문자열로 반환합니다.

다음 표에는 문자열로 변환하는 몇 가지 예가 나와 있습니다:

예제
결과
{$toString: true}
"true"
{$toString: false}
"false"
{$toString: 2.5}
"2.5"
{$toString: NumberInt(2)}
"2"
{$toString: NumberLong(1000)}
"1000"
{$toString: ObjectId("5ab9c3da31c2ab715d421285")}
"5ab9c3da31c2ab715d421285"
{$toString: ISODate("2018-03-27T16:58:51.538Z")}
"2018-03-27T16:58:51.538Z"

다음 문서를 사용하여 컬렉션 orders를 생성합니다.

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, zipcode: 93445 },
{ _id: 2, item: "almonds", qty: 2, zipcode: "12345-0030" },
{ _id: 3, item: "peaches", qty: 5, zipcode: 12345 },
] )

orders 컬렉션에 대한 다음 집계 작업은 문자열 값을 기준으로 정렬하기 전에 zipcode를 문자열로 변환합니다.

// Define stage to add convertedZipCode field with the converted zipcode value
zipConversionStage = {
$addFields: {
convertedZipCode: { $toString: "$zipcode" }
}
};
// Define stage to sort documents by the converted zipcode
sortStage = {
$sort: { "convertedZipCode": 1 }
};
db.orders.aggregate( [
zipConversionStage,
sortStage
] )

이 작업은 다음 문서를 반환합니다.

{
_id: 3,
item: 'peaches',
qty: 5,
zipcode: 12345,
convertedZipCode: '12345'
},
{
_id: 2,
item: 'almonds',
qty: 2,
zipcode: '12345-0030',
convertedZipCode: '12345-0030'
},
{
_id: 1,
item: 'apple',
qty: 5,
zipcode: 93445,
convertedZipCode: '93445'
}

참고

변환 작업에 오류가 발생하면 애그리게이션 작업이 중지되고 오류가 발생합니다. 이 동작을 재정의하려면 $convert 를 대신 사용하세요.

← topN(집계 누산기)

이 페이지의 내용