对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$serializeEJSON(表达式操作符)

$serializeEJSON

8.3版本新增。

将BSON值转换为扩展JSON (EJSON) 格式。结果是带有EJSON类型包装器的BSON document,然后可以使用 $toString 将其转换为JSON string。

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

$serializeEJSON 接受包含以下字段的文档:

字段
类型
必要性
说明

input

表达式(expression)

必需

要转换为扩展JSON格式的BSON值。

relaxed

布尔

Optional

指定是否使用宽松扩展JSON格式。

  • 如果为 true,$serializeEJSON 使用宽松扩展JSON格式,该格式将数字类型(Int32、Int64、Double)表示为原生JSON数字,以提高可读性。

  • 如果为 false 或未指定,则 $serializeEJSON 使用规范扩展JSON格式,该格式保留所有BSON 类型的类型信息。

默认: false

onError

表达式(expression)

Optional

如果操作在转换期间遇到错误,则返回该值。

如果未指定,则在发生错误时,操作会引发错误并停止。

下表显示了常见BSON 类型如何转换为扩展JSON:

BSON 类型
规范扩展 JSON
宽松扩展 JSON

Int32

{"$numberInt": "42"}

42

Int64

{"$numberLong": "42"}

42

double

{"$numberDouble": "42.5"}

42.5

ObjectId

{"$oid": "507f1f77bcf86cd799439011"}

与 Canonical 相同

Date

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

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

二进制文件

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

与 Canonical 相同

正则表达式

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

与 Canonical 相同

如果 input 值为 null 或缺失,则 $serializeEJSON 返回 null。

本页上的示例使用来自 sample_mflix 数据集的数据。有关如何将此数据集加载到您的自管理 MongoDB 部署中的详细信息,请参阅 加载示例数据集。如果您对示例数据库进行了任何修改,您可能需要删除并重新创建数据库,才能运行此页面上的示例。

以下示例将电影document转换为规范扩展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 string是没有空格的单行。

您可以序列化特定字段而不是整个document:

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" } } } } }])
给本页内容打分