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()方法有以下字段:
value | BSON object | EJSON.stringify() transformsEJSON.stringify()转换 | |||||||
replacer | array or function |
| |||||||
spacer | integer or string |
| |||||||
options | boolean |
|
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 要控制如何将文档传递给EJSON,请使用mongosh cursor method iterators.mongosh游标方法迭代器之一。
.toArray() | |
.foreach | |
.next() |
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 EJSON格式化每个文档的quantity and cost for each document.quantity和cost。
[{"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 要转换字段值,请使用JavaScript函数设置replacer option. For example: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函数更新两个字段_id和quantity。
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 该示例查询2023年7月的sales collection for sales in July, 2023.sales集合。
sales_2023_07stores 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.jsonfile in the directory where you ranmongosh.mongosh的目录中的sales2023_07.json文件。
Run from the Command Line从命令行运行
To run a query from the operating system shell, use the 要从操作系统shell运行查询,请使用--eval option.--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:
--quietsuppresses the抑制mongoshconnection informationmongosh连接信息--evalcalls the调用findmethodfind方法.forEachis a JavaScript method that tells是一种JavaScript方法,告诉mongoshto iterate over the responsemongosh在响应上迭代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"
}
}
ois the BSON value that是EJSON.stringify()converts on each iteration of.forEach().EJSON.stringify()在每次.forEach()迭代时转换的BSON值。nullis a place holder for an optional是可选replacer. When thereplaceris absent,EJSON.stringify()returns all fields that have a defined value.replacer的占位符。当replacer不存在时,EJSON.stringify()返回所有具有定义值的字段。3is the是spacervalue.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.mongosh和mongo中运行一个示例查询,以查看不同的格式。
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了解更多
- EJSON
documentation文档 Mozilla Developer Network JSON.stringify() documentationMozilla开发者网络JSON.stringify()文档