Docs Menu
Docs Home
/ /

$serializeEJSON (표현식 연산자)

$serializeEJSON

버전 8.3에 추가 되었습니다.

BSON 값을 확장 JSON (EJSON) 형식으로 변환합니다. 결과는 을 사용하여 JSON 문자열로 변환할 수 있는 EJSON 유형 래퍼가 있는 BSON 문서 $toString 입니다.

{
$serializeEJSON: {
input: <expression>,
relaxed: <boolean>,
onError: <expression>
}
}

$serializeEJSON 은 다음 필드가 있는 문서를 가져옵니다.

필드
유형
필요성
설명

input

표현식

필수 사항

확장 JSON 형식으로 변환할 BSON 값입니다.

relaxed

부울

옵션

완화된 확장 JSON 형식을 사용할지 여부를 지정합니다.

  • true인 경우 $serializeEJSON 는 가독성을 높이기 위해 숫자 유형(Int32, Int64, Double)을 네이티브 JSON 숫자로 나타내는 Relaxed Extended JSON 형식을 사용합니다.

  • false 이거나 지정되지 않은 경우 $serializeEJSON 는 모든 BSON types에 대한 유형 정보를 보존하는 Canonical Extended JSON 형식을 사용합니다.

기본값입니다: false

onError

표현식

옵션

변환 중에 작업에 오류가 발생하는 경우 반환할 값입니다.

지정하지 않은 경우 오류가 발생하면 작업이 오류를 발생시키고 중지됩니다.

다음 표는 일반적인 BSON types가 Extended JSON 으로 변환되는 방법을 보여줍니다.

BSON 유형
표준 확장 JSON
완화된 확장 JSON

Int32

{"$numberInt": "42"}

42

Int64

{"$numberLong": "42"}

42

Double

{"$numberDouble": "42.5"}

42.5

ObjectId

{"$oid": "507f1f77bcf86cd799439011"}

표준과 동일

날짜

{"$date": {"$numberLong": "1609459200000"}}

{"$date": "2021-01-01T00:00:00.000Z"}

바이너리

{"$binary": {"base64": "AQIDBA==", "subType": "00"}}

표준과 동일

정규 표현식

{"$regularExpression": {"pattern": "abc", "options": "i"}}

표준과 동일

input 값이 null이거나 누락된 경우 $serializeEJSON 은 null을 반환합니다.

이 페이지의 예제에서는 sample_mflix 샘플 데이터 세트의 데이터를 사용합니다. 이 데이터 세트를 자체 관리형 MongoDB 배포서버에 로드하는 방법에 대한 자세한 내용은 샘플 데이터 세트 로드를 참조하세요. 샘플 데이터베이스를 수정한 경우 이 페이지의 예시를 실행 하려면 데이터베이스를 제거하고 다시 만들어야 할 수 있습니다.

다음 예시 영화 문서 표준 확장 JSON 형식으로 변환합니다.

db.movies.aggregate([
{
$match: { title: "Inception" }
},
{
$project: {
ejson: { $serializeEJSON: { input: "$$ROOT" } }
}
}
])
{
_id: ObjectId("573a1398f29313caabcea974"),
ejson: {
_id: { $oid: "573a1398f29313caabcea974" },
title: "Inception",
year: { $numberInt: "2010" },
runtime: { $numberInt: "148" },
released: { $date: { $numberLong: "1279238400000" } },
cast: [
"Leonardo DiCaprio",
"Joseph Gordon-Levitt",
"Ellen Page",
"Tom Hardy"
],
genres: [ "Action", "Sci-Fi", "Thriller" ],
directors: [ "Christopher Nolan" ]
}
}

다음 예시 더 읽기 쉬운 출력을 위해 relaxed 옵션을 사용합니다.

db.movies.aggregate([
{
$match: { title: "Inception" }
},
{
$project: {
ejson: {
$serializeEJSON: {
input: "$$ROOT",
relaxed: true
}
}
}
}
])
{
_id: ObjectId("573a1398f29313caabcea974"),
ejson: {
_id: { $oid: "573a1398f29313caabcea974" },
title: "Inception",
year: 2010,
runtime: 148,
released: { $date: "2010-07-16T00:00:00.000Z" },
cast: [
"Leonardo DiCaprio",
"Joseph Gordon-Levitt",
"Ellen Page",
"Tom Hardy"
],
genres: [ "Action", "Sci-Fi", "Thriller" ],
directors: [ "Christopher Nolan" ]
}
}

EJSON 결과를 JSON 문자열로 변환하려면 $serializeEJSON 를 와 $toString 결합합니다.

db.movies.aggregate([
{
$match: { title: "The Godfather" }
},
{
$project: {
title: 1,
jsonString: {
$toString: {
$serializeEJSON: { input: "$$ROOT" }
}
}
}
}
])
[
{
_id: '573a13c5f29313caabd6ee62',
title: 'The Godfather',
jsonString: `{"_id":"573a13c5f29313caabd6ee62",` +
`"fullplot":"When the aging head of a famous crime family decides to transfer his position to one of his subalterns, a series of unfortunate events start happening to the family, and a war begins between all the well-known families leading to insolence, deportation, murder and revenge, and ends with the favorable successor being finally chosen.",` +
`"imdb":{"rating":9.2,"votes":1038358,"id":68646},` +
`"year":1972,` +
`"plot":"The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",` +
`"genres":["Crime","Drama"],` +
`"rated":"R",` +
`"metacritic":100,` +
`"title":"The Godfather",` +
`"lastupdated":"2015-09-02 00:08:23.680000000",` +
`"languages":["English","Italian","Latin"],` +
`"writers":["Mario Puzo (screenplay)","Francis Ford Coppola (screenplay)","Mario Puzo (novel)"],` +
`"type":"movie",` +
`"tomatoes":{"website":"http://www.thegodfather.com","viewer":{"rating":4.4,"numReviews":725773,"meter":98},"dvd":{"$date":"2001-10-09T00:00:00.000Z"},"critic":{"rating":9.2,"numReviews":84,"meter":99},"lastUpdated":{"$date":"2015-09-12T17:15:13.000Z"},"consensus":"One of Hollywood's greatest critical and commercial successes, The Godfather gets everything right; not only did the movie transcend expectations, it established new benchmarks for American cinema.","rotten":1,"production":"Paramount Pictures","fresh":83},` +
`"poster":"https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SY1000_SX677_AL_.jpg",` +
`"num_mflix_comments":131,` +
`"released":{"$date":"1972-03-24T00:00:00.000Z"},` +
`"awards":{"wins":33,"nominations":19,"text":"Won 3 Oscars. Another 30 wins & 19 nominations."},` +
`"countries":["USA"],` +
`"cast":["Marlon Brando","Al Pacino","James Caan","Richard S. Castellano"],` +
`"directors":["Francis Ford Coppola"],` +
`"runtime":175}`
}
]

참고

이전 예시 의 jsonString 필드 가독성을 위해 형식이 다시 지정되었습니다. 실제 출력에서 JSON 문자열은 공백이 없는 한 줄입니다.

전체 문서가 아닌 특정 필드를 직렬화할 수 있습니다.

db.movies.aggregate([
{
$match: { year: { $gte: 2010 } }
},
{
$project: {
title: 1,
metadataEJSON: {
$serializeEJSON: {
input: {
releaseDate: "$released",
runtime: "$runtime",
imdbRating: "$imdb.rating"
}
}
}
}
}
])
[
{
_id: '573a13c5f29313caabd6ee61',
title: 'Inception',
metadataEJSON: {
releaseDate: { '$date': '2010-07-16T00:00:00.000Z' },
runtime: 148,
imdbRating: 8.8
}
}
]

다음 예시 onError 를 사용하여 직렬화가 실패할 경우 대체 값을 제공합니다.

db.movies.aggregate([
{
$project: {
title: 1,
ejson: {
$serializeEJSON: {
input: "$customField",
onError: { error: "Serialization failed" }
}
}
}
}
])

돌아가기

$second

이 페이지의 내용