Definición
$serializeEJSONNuevo en la versión 8.3.
Convierte los valores BSON al formato JSON extendido (EJSON). El resultado es un document BSON con contenedores de tipo EJSON que luego se pueden convertir en una string JSON utilizando
$toString.
Sintaxis
{ $serializeEJSON: { input: <expression>, relaxed: <boolean>, onError: <expression> } }
$serializeEJSON toma un documento con los siguientes campos:
Campo | Tipo | Necesidad | Descripción |
|---|---|---|---|
| expresión | Requerido | El valor BSON a convertir al formato JSON extendido. |
| Booleano | Opcional | Especifica si se debe usar el formato Relaxed Extended JSON.
Por defecto: |
| expresión | Opcional | Valor a devolver si la operación encuentra un error durante la conversión. Si no se especifica, cuando ocurre un error, la operación genera un error y se detiene. |
Comportamiento
Comparación de los formatos canónicos y relajados
La siguiente tabla muestra cómo se convierten los BSON types comunes a JSON ampliado:
Tipo BSON | JSON extendido canónico | JSON extendido relajado |
|---|---|---|
Int32 |
|
|
Int64 |
|
|
Double |
|
|
ObjectId |
| Same as Canonical |
fecha |
|
|
Binario |
| Same as Canonical |
Expresión regular |
| Same as Canonical |
Valores nulos y faltantes
Si el valor input es nulo o falta, $serializeEJSON devolverá null.
Ejemplos
Los ejemplos de esta página utilizan datos del conjunto de datos de muestra_mflix. Para obtener detalles sobre cómo cargar este conjunto de datos en su implementación autogestionada de MongoDB, consulte Cargue el conjunto de datos de muestra. Si realizaste modificaciones en las bases de datos de ejemplo, es posible que necesites descartar y volver a crear las bases de datos para ejecutar los ejemplos de esta página.
Ejemplo canónico de JSON extendido
El siguiente ejemplo convierte un document de película al formato Canonical Extended 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" ] } }
Ejemplo de Extended JSON relajado
El siguiente ejemplo utiliza la opción relaxed para obtener una salida más legible:
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" ] } }
Convertir en JSON string
Para convertir el resultado EJSON a una string JSON, combina $serializeEJSON con $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}` } ]
Nota
El campo jsonString en el ejemplo anterior está remodelado para mejorar su legibilidad. En la salida real, la string JSON es una sola línea sin espacios en blanco.
Serializar campos específicos
Puedes serializar campos específicos en lugar de document completos:
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 } } ]
Use onError para el manejo de errores
El siguiente ejemplo utiliza onError para proporcionar un valor alternativo si la serialización falla:
db.movies.aggregate([ { $project: { title: 1, ejson: { $serializeEJSON: { input: "$customField", onError: { error: "Serialization failed" } } } } } ])
Obtén más información
La interfaz MongoDB Shell proporciona métodos integrados para ayudar a trabajar con JSON extendido. Para obtener más información, consulte EJSON.