AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

$toObjectId(표현식 연산자)

$toObjectId

값을 ObjectId()로 변환합니다. 값을 ObjectId로 변환할 수 없는 경우 $toObjectId는 오류를 발생시킵니다. 값이 null이거나 누락된 경우, $toObjectId는 null을 반환합니다.

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

{ $toObjectId: <expression>}

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

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

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

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

입력 유형
행동

문자열

길이 24의 16진수 문자열에 대한 ObjectId를 반환합니다.

길이가 24인 16진수 문자열이 아닌 문자열 값은 변환할 수 없습니다.

다음 표에는 날짜로의 몇 가지 변환 예가 나열되어 있습니다.

예시
결과

{$toObjectId: "5ab9cbfa31c2ab715d42129e"}

ObjectId("5ab9cbfa31c2ab715d42129e")

{$toObjectId: "5ab9cbfa31c2ab715d42129"}

오류

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

db.orders.insertMany( [ { _id: "5ab9cbe531c2ab715d42129a", item: "apple", qty: 10 }, { _id: ObjectId("5ab9d0b831c2ab715d4212a8"), item: "pie", qty: 5 }, { _id: ObjectId("5ab9d2d331c2ab715d4212b3"), item: "ice cream", qty: 20 }, { _id: "5ab9e16431c2ab715d4212b4", item: "almonds", qty: 50 },] )

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

// Define stage to add convertedId field with converted _id value idConversionStage = { $addFields: { convertedId: { $toObjectId: "$_id" } }}; // Define stage to sort documents by the converted qty values sortStage = { $sort: { "convertedId": -1 }}; db.orders.aggregate( [ idConversionStage, sortStage] )

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

{ _id: '5ab9e16431c2ab715d4212b4', item: 'almonds', qty: 50, convertedId: ObjectId("5ab9e16431c2ab715d4212b4")},{ _id: ObjectId("5ab9d2d331c2ab715d4212b3"), item: 'ice cream', qty: 20, convertedId: ObjectId("5ab9d2d331c2ab715d4212b3")},{ _id: ObjectId("5ab9d0b831c2ab715d4212a8"), item: 'pie', qty: 5, convertedId: ObjectId("5ab9d0b831c2ab715d4212a8")},{ _id: '5ab9cbe531c2ab715d42129a', item: 'apple', qty: 10, convertedId: ObjectId("5ab9cbe531c2ab715d42129a")}

참고

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

이 페이지 평가하기

이 페이지의 내용