Docs Home / mongosh / Reference / EJSON

EJSON.stringify()

The EJSON.stringify() method converts BSON values to strings.EJSON.stringify()方法将BSON值转换为字符串。

Syntax语法

The EJSON.stringify() method takes a BSON object as input and optional modifiers that control the format of the output string.EJSON.stringify()方法将BSON对象作为输入,并使用可选修饰符控制输出字符串的格式。

EJSON.stringify(BSON object, [replacer], [space], [options])

Command Fields命令字段

The EJSON.stringify() method has these fields:EJSON.stringify()方法有以下字段:

Field字段Type类型Necessity必要性Description描述
valueBSON objectRequired必需Object EJSON.stringify() transforms对象EJSON.stringify()转换
replacerarray or functionOptional可选

Modifies output. If the value exists but it is not an array or a function, EJSON.stringify() returns all document fields.修改输出。如果该值存在,但不是数组或函数,则EJSON.stringify()返回所有文档字段。

replacer can be an array or a function.可以是数组或函数。

ValueEffect效果
arrayAn array of document fields to include in the output. The array elements must specify the field names to include in the returned JSON string.要包含在输出中的文档字段数组。数组元素必须指定要包含在返回的JSON字符串中的字段名。
function

A function that takes two parameters, key and value. key provides the function's this context. EJSON returns the transformed value.一个接受两个参数的函数,keyvaluekey提供函数的this上下文。EJSON返回转换后的值。

The function is run for each object. The object values are replaced with the function's return value.该函数为每个对象运行。对象值将替换为函数的返回值。

For an example, see Use a Function to Transform Output Fields.例如,请参阅使用函数变换输出字段。

spacerinteger or stringOptional可选

Controls spacing in the output. Use null as a place holder for replacer if you only want to specify the spacer option.控制输出中的间距。如果您只想指定spacer选项,请使用null作为replacer的占位符。

ValueEffect效果
integerThe number of spaces to indent each level. 10 is the maximum.每层缩进的空格数。10是最大值。
stringA character to use to indent each level. This option produces invalid JSON if you use a character other than a space or tab. 用于缩进每个级别的字符。如果使用空格或制表符以外的字符,此选项将生成无效的JSON。For more information see JSON.stringify()有关更多信息,请参阅JSON.stringify()
optionsbooleanOptional可选

Additional configuration options其他配置选项

Option选项Default默认值Meaning意义
relaxedtrueEnable relaxed mode for Extended JSON. Returns native JSON types instead of attaching BSON type information where applicable.为扩展JSON启用宽松模式。返回本机JSON类型,而不是在适用的情况下附加BSON类型信息。

Behavior行为

You can call the EJSON interface from inside an interactive mongosh session or from the system command line using --eval.您可以从交互式mongosh会话内部或使用--eval从系统命令行调用EJSON接口。

Call the EJSON interface from an interactive session:从交互式会话调用EJSON接口:

EJSON.stringify( db.sales.find().toArray(), null, 2  )

Call the EJSON interface from the system command line:从系统命令行调用EJSON接口:

mongosh --eval "EJSON.stringify( db.sales.find().toArray(), null, 2  )"

To control how documents are passed to EJSON, use one of the mongosh cursor method iterators.要控制如何将文档传递给EJSON,请使用mongosh游标方法迭代器之一。

Iterator迭代器Characteristics特性
.toArray()Blocking, buffers the entire result阻塞、缓冲整个结果
.foreachNon-blocking, prints documents one-by-one无阻塞,逐个打印文档
.next()Non-blocking, manually iterate over results无阻塞,手动迭代结果

Examples示例

To try these examples, first create a sales collection in the test database:要尝试这些示例,首先在test数据库中创建一个sales集合:

db.sales.insertMany( [
{ custId: 345, purchaseDate: ISODate("2023-07-04"), quantity: 4, cost: Decimal128("100.60"), },
{ custId: 346, purchaseDate: ISODate("2023-07-12"), quantity: 3, cost: Decimal128("175.45"), },
{ custId: 486, purchaseDate: ISODate("2023-08-01"), quantity: 9, cost: Decimal128("200.53"), },
] )

Change Output Spacing更改输出间距

To increase indentation between levels, set the spacing option.要增加标高之间的缩进,请设置spacing选项。

EJSON.stringify( db.sales.findOne( { custId: 345 } ), null , 5 )

EJSON.stringify() indents each document level five spaces.将每个文档缩进五级空格。

{
"_id": {
"$oid": "64da90c1175f5091debcab26"
},
"custId": 345,
"purchaseDate": {
"$date": "2023-07-04T00:00:00Z"
},
"quantity": 4,
"cost": {
"$numberDecimal": "100.60"
}
}

Select Output Fields选择输出字段

To select a subset of document fields, use an array to set the replace option.要选择文档字段的子集,请使用数组设置replace选项。

EJSON.stringify( db.sales.find().toArray(), [ "quantity", "cost" ] )

EJSON formats the quantity and cost for each document.EJSON格式化每个文档的quantitycost

[{"quantity":4,"cost":{}},{"quantity":3,"cost":{}},{"quantity":9,"cost":{}}]

The spacing option is not specified in this example, so EJSON returns the selected fields on a single line.此示例中未指定spacing选项,因此EJSON在一行上返回所选字段。

Use a Function to Transform Output Fields使用函数转换输出字段

To transform field values, use a JavaScript function to set the replacer option. For example:要转换字段值,请使用JavaScript函数设置replacer选项。例如:

let queryResults = db.sales.find().toArray()
let replacer = function( key, value ){
if ( key === '_id' ) {
value = undefined;
}
if ( key === 'quantity' ) {
value = 2 * value;
}

return value;
}

EJSON.stringify( queryResults, replacer, 3 )

The function runs recursively against the input object.该函数对输入对象递归运行。

Example output:输出示例:

[
{
"custId": 345,
"purchaseDate": {
"$date": "2023-07-04T00:00:00Z"
},
"quantity": 8,
"cost": {
"$numberDecimal": "100.60"
}
},
{
"custId": 346,
"purchaseDate": {
"$date": "2023-07-12T00:00:00Z"
},
"quantity": 6,
"cost": {
"$numberDecimal": "175.45"
}
},
{
"custId": 486,
"purchaseDate": {
"$date": "2023-08-01T00:00:00Z"
},
"quantity": 18,
"cost": {
"$numberDecimal": "200.53"
}
}
]

The replacer function updates two fields, _id and quantity.replacer函数更新两个字段_idquantity

EJSON.stringify() ignores fields with undefined values, so setting _id: undefined removes the _id field from the output string.忽略具有未定义值的字段,因此设置_id: undefined会从输出字符串中删除_id字段。

The function also modifies the quantity field in the output string. All of the quantity values are multiplied by two in the output string. EJSON.stringify() does not update the collection.该函数还修改了输出字符串中的quantity字段。所有quantity值在输出字符串中都乘以2。EJSON.stringify()不会更新集合。

Use a Function to Transform Output Fields in Nested Objects使用函数转换嵌套对象中的输出字段

Create the salesWithAddress collection with nested addresses:使用嵌套地址创建salesWithAddress集合:

db.salesWithAddress.insertMany( [
{ custId: 345, purchaseDate: ISODate("2023-07-04"),
quantity: 4, cost: Decimal128("100.60"),
address: { number: 100, street: "Main Street", ZIP: 12345 } },
{ custId: 346, purchaseDate: ISODate("2023-07-12"),
quantity: 3, cost: Decimal128("175.45"),
address: { number: 200, street: "East Street", ZIP: 12345 } }
] )

The following example uses a replacer function to change the ZIP codes for the addresses to 55555:以下示例使用replacer函数将地址的邮政编码更改为55555

// Retrieve the salesWithAddress contents as an array and save in queryResults以数组形式检索salesWithAddress内容并保存在queryResults中
let queryResults = db.salesWithAddress.find().toArray()

// Define a replacer function to change the ZIP codes定义替换函数以更改邮政编码
let replacer = function( key, value ) {
if (key === 'address') {
value.ZIP = 55555;
}
return value;
}

// Run EJSON.stringify() to change the ZIP codes in queryResults运行EJSON.stringify()以更改queryResults中的邮政编码
EJSON.stringify( queryResults, replacer, 3 )

Example output:输出示例:

[
{
"_id": {
"$oid": "65498c6562f443aa1490070f"
},
"custId": 345,
"purchaseDate": {
"$date": "2023-07-04T00:00:00Z"
},
"quantity": 4,
"cost": {
"$numberDecimal": "100.60"
},
"address": {
"number": 100,
"street": "Main Street",
"ZIP": 55555
}
},
{
"_id": {
"$oid": "65498c6562f443aa14900710"
},
"custId": 346,
"purchaseDate": {
"$date": "2023-07-12T00:00:00Z"
},
"quantity": 3,
"cost": {
"$numberDecimal": "175.45"
},
"address": {
"number": 200,
"street": "East Street",
"ZIP": 55555
}
}
]

Use a Function to Replace BSON Strings使用函数替换BSON字符串

For a list of BSON data types and the corresponding numeric codes, see BSON Types.有关BSON数据类型和相应数字代码的列表,请参阅BSON类型

The following example uses a replacer function to replace the BSON strings with the string "This is a string":以下示例使用replacer函数将BSON字符串替换为字符串"This is a string"

// Retrieve the salesWithAddress contents as an array and save in queryResults以数组形式检索salesWithAddress内容并保存在queryResults中
let queryResults = db.salesWithAddress.find().toArray()

// Define a replacer function to replace the strings定义一个replacer函数来替换字符串
let replacer = function( key, value ) {
if (typeof value === "string") {
return "This is a string";
}
return value;
}

// Run EJSON.stringify() to replace the strings in queryResults运行EJSON.stringify()替换queryResults中的字符串
EJSON.stringify( queryResults, replacer, 3 )

Example output:输出示例:

[
{
"_id": {
"$oid": "This is a string"
},
"custId": 345,
"purchaseDate": {
"$date": "This is a string"
},
"quantity": 4,
"cost": {
"$numberDecimal": "This is a string"
},
"address": {
"number": 100,
"street": "This is a string",
"ZIP": 12345
}
},
{
"_id": {
"$oid": "This is a string"
},
"custId": 346,
"purchaseDate": {
"$date": "This is a string"
},
"quantity": 3,
"cost": {
"$numberDecimal": "This is a string"
},
"address": {
"number": 200,
"street": "This is a string",
"ZIP": 12345
}
}
]

Write to a File from Inside mongosh从Inside mongosh写入文件

To write to a file from within mongosh, use the fs API. Use EJSON.stringify() to format the string that you pass to fs.要从mongosh中写入文件,请使用fs API。使用EJSON.stringify()格式化传递给fs的字符串。

const sales_2023_07 = db.sales.find(
{
purchaseDate:
{
$gte: ISODate( "2023-07-01" ),
$lte: ISODate( "2023-07-31" )
}
}
)

fs.writeFileSync(
'sales_2023_07.json',
EJSON.stringify( sales_2023_07.toArray(), null, 2 )
)

The example queries the sales collection for sales in July, 2023.该示例查询2023年7月的sales集合。

  • sales_2023_07 stores a MongoDB BSON object.存储MongoDB BSON对象。
  • EJSON.stringify() formats the object as a JSON string.将对象格式化为JSON字符串。
  • fs.writeFileSync() writes the formatted string to the sales_2023_07.json file in the directory where you ran mongosh.将格式化的字符串写入运行mongosh的目录中的sales2023_07.json文件。

Run from the Command Line从命令行运行

To run a query from the operating system shell, use the --eval option.要从操作系统shell运行查询,请使用--eval选项。

# Note: This example is formatted to fit on the page.

mongosh --quiet \
--eval "db.sales.find().forEach( \
o => print( EJSON.stringify( o ) ) )"

The command returns a single line of JSON for each document:该命令为每个文档返回一行JSON:

  • --quiet suppresses the mongosh connection information抑制mongosh连接信息
  • --eval calls the find method调用find方法
  • .forEach is a JavaScript method that tells mongosh to iterate over the response是一种JavaScript方法,告诉mongosh在响应上迭代
  • EJSON.stringify() converts each document to JSON将每个文档转换为JSON

The output is:输出为:

{"_id":{"$oid":"64da90c1175f5091debcab26"},"custId":345,"purchaseDate":{"$date":"2023-07-04T00:00:00Z"},"quantity":4,"cost":{"$numberDecimal":"100.60"}}
{"_id":{"$oid":"64da90c1175f5091debcab27"},"custId":346,"purchaseDate":{"$date":"2023-07-12T00:00:00Z"},"quantity":3,"cost":{"$numberDecimal":"175.45"}}
{"_id":{"$oid":"64da90c1175f5091debcab28"},"custId":486,"purchaseDate":{"$date":"2023-08-01T00:00:00Z"},"quantity":9,"cost":{"$numberDecimal":"200.53"}}

The single-line output format is convenient for scripting. EJSON.stringify() can also produce human-readable formatting:单行输出格式便于脚本编写。EJSON.stringify()也可以生成人类可读的格式:

# Note: This example is formatted to fit on the page.

mongosh --quiet \
--eval "db.sales.find().forEach( \
o => print( EJSON.stringify(o, null, 3 ) ) )"

The output is:输出为:

# Note: This is only the first document.

{
"_id": {
"$oid": "64da90c1175f5091debcab26"
},
"custId": 345,
"purchaseDate": {
"$date": "2023-07-04T00:00:00Z"
},
"quantity": 4,
"cost": {
"$numberDecimal": "100.60"
}
}
  • o is the BSON value that EJSON.stringify() converts on each iteration of .forEach().EJSON.stringify()在每次.forEach()迭代时转换的BSON值。
  • null is a place holder for an optional replacer. When the replacer is absent, EJSON.stringify() returns all fields that have a defined value.是可选replacer的占位符。当replacer不存在时,EJSON.stringify()返回所有具有定义值的字段。
  • 3 is the spacer value. spacer值。It tells EJSON.stringify() to indent each new level by 3 spaces.它告诉EJSON.stringify()将每个新级别缩进3个空格。

If the you want the output string to have additional type information, add the { relaxed: false } option:如果您希望输出字符串具有其他类型信息,请添加{ relaxed: false }选项:

# Note: This example is formatted to fit on the page.

mongosh --quiet \
--eval "db.sales.find().forEach( \
o => print( \
EJSON.stringify( o, null, 3, { relaxed: false } ) \
) )"

The output is:输出为:

# Note: This is only the first document.

{
"_id": {
"$oid": "64da90c1175f5091debcab26"
},
"custId": {
"$numberInt": "345"
},
"purchaseDate": {
"$date": {
"$numberLong": "1688428800000"
}
},
"quantity": {
"$numberInt": "4"
},
"cost": {
"$numberDecimal": "100.60"
}
}

Filter Output Fields筛选器输出字段

EJSON.stringify() provides formatting options that reduce the need for an additional JSON parser like jq.提供了格式化选项,减少了对jq等额外JSON解析器的需求。

# Note: This example is formatted to fit on the page.

mongosh --quiet \
--eval "EJSON.stringify( \
db.sales.find( {}, \
{ _id: 0, custId: 1, quantity: 1 } ).toArray(), null, 2 \
);"

The output is:输出为:

[
{
"custId": 345,
"quantity": 4
},
{
"custId": 346,
"quantity": 3
},
{
"custId": 486,
"quantity": 9
}
]

Legacy 遗留的tojsononeline()

The mongosh shell returns output that differs from the legacy mongo shell. mongosh shell返回的输出与传统mongo shell不同。If you have scripts that require the output to be formatted in a similar way to the legacy mongo shell, try reformatting the mongosh output with EJSON.stringify().如果脚本要求输出以与传统mongo shell类似的方式格式化,请尝试使用EJSON.stringify()重新格式化mongosh输出。

Run a sample query in mongosh and mongo to see the different formats.mongoshmongo中运行一个示例查询,以查看不同的格式。

db.sales.find( { custId: 345 } )

Legacy output:传统输出:

{ "_id" : ObjectId("64da90c1175f5091debcab26"), "custId" : 345, "purchaseDate" : ISODate("2023-07-04T00:00:00Z"), "quantity" : 4, "cost" : NumberDecimal("100.60") }

mongosh output:

db.sales.find( { custId: 345 } )
[
{
_id: ObjectId("64da90c1175f5091debcab26"),
custId: 345,
purchaseDate: ISODate("2023-07-04T00:00:00.000Z"),
quantity: 4,
cost: Decimal128("100.60")
}
]

Reformat the output with EJSON.stringify().使用EJSON.stringify()重新格式化输出。

EJSON.stringify( db.sales.find( { custId: 345 } ).toArray() )
[{"_id":{"$oid":"64da90c1175f5091debcab26"},"custId":345,"purchaseDate":{"$date":"2023-07-04T00:00:00Z"},"quantity":4,"cost":{"$numberDecimal":"100.60"}}]

Learn More了解更多