文档菜单
文档首页
/
MongoDB Shell
/ /

EJSON.stringify()

本页内容

  • 语法
  • 命令字段
  • 行为
  • 示例
  • 更改输出间距
  • 选择输出字段
  • 使用函数转换输出字段
  • 使用函数在嵌套对象中转换输出字段
  • 使用函数替换BSON字符串
  • 从mongosh内部写入文件
  • 从命令行运行
  • 过滤输出字段
  • 旧版tojsononeline()
  • 了解更多

EJSON.stringify() 方法将BSON值转换为字符串。

EJSON.stringify() 方法接受一个 BSON 对象作为输入以及可选的修饰符,用于控制输出字符串的格式。

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

EJSON.stringify() 方法具有以下字段

字段
类型
必要性
描述
value
BSON对象
必需
对象EJSON.stringify()转换
replacer
数组或函数
可选

修改输出。如果值存在但不是数组或函数,EJSON.stringify()将返回所有文档字段。

replacer可以是数组或函数。

效果
数组
要包含在输出中的文档字段数组。数组元素必须指定要包含在返回的 JSON 字符串中的字段名称。
函数

一个接受两个参数的函数,keyvaluekey提供了函数的this上下文。EJSON返回转换后的value

该函数为每个对象执行。对象值被替换为函数的返回值。

例如,请参阅使用函数转换输出字段.

间隔
整数或字符串
可选

控制输出中的间隔。如果只想指定spacer选项,请使用null作为replacer的占位符。

效果
整数
缩进每个级别的空格数。10是最大值。
字符串
用于缩进每个级别的字符。此选项如果您使用除空格或制表符之外的字符,将生成无效的JSON。有关更多信息,请参阅JSON.stringify()
选项
布尔值
可选

其他配置选项

选项
默认值
含义
relaxed
true
启用扩展JSON的宽松模式。在适用的情况下返回原生JSON类型,而不是附加BSON类型信息。

您可以从交互式mongosh会话或从系统命令行使用--eval调用EJSON接口。

从交互式会话调用EJSON接口

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

从系统命令行调用EJSON接口

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

要控制如何将文档传递给EJSON,请使用mongosh游标方法迭代器之一。

迭代器
特性
阻塞,缓冲整个结果
非阻塞,逐个打印文档
非阻塞,手动遍历结果

要尝试这些示例,首先在 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"), },
] )

要增加层级间的缩进,请设置 spacing 选项。

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

EJSON.stringify() 为每个文档级别缩进五个空格。

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

要选择文档的子集字段,请使用数组设置 replace 选项。

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

EJSON 为每个文档的 quantitycost 格式化。

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

此示例中未指定 spacing 选项,因此 EJSON 将选定的字段放在一行上返回。

要转换字段值,请使用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 )

函数递归地对输入对象运行。

示例输出

[
{
"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"
}
}
]

replacer 函数更新了两个字段,_idquantity

EJSON.stringify() 忽略具有未定义值的字段,因此设置 _id: undefined 会从输出字符串中删除 _id 字段。

函数还修改了输出字符串中的 quantity 字段。输出字符串中所有的 quantity 值都乘以二。 EJSON.stringify() 不会更新集合。

创建带有嵌套地址的 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 } }
] )

以下示例使用 replacer 函数将地址的邮政编码更改为 55555

// Retrieve the salesWithAddress contents as an array and save
// in 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, replacer, 3 )

示例输出

[
{
"_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
}
}
]

有关BSON数据类型及其对应数字代码的列表,请参阅BSON类型。

以下示例使用一个replacer函数将BSON字符串替换为字符串"This is a string"

// Retrieve the salesWithAddress contents as an array and save
// in queryResults
let queryResults = db.salesWithAddress.find().toArray()
// Define a replacer function to replace the strings
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, replacer, 3 )

示例输出

[
{
"_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
}
}
]

要从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 )
)

以下示例查询2023年7月的sales集合中的销售数据。

  • sales_2023_07存储一个MongoDB BSON对象。

  • EJSON.stringify()将对象格式化为JSON字符串。

  • fs.writeFileSync()将格式化的字符串写入你在运行mongosh的目录中的sales_2023_07.json文件。

要从操作系统shell中运行查询,请使用--eval 选项。

# Note: This example is formatted to fit on the page.
mongosh --quiet \
--eval "db.sales.find().forEach( \
o => print( EJSON.stringify( o ) ) )"

命令为每个文档返回一行JSON

  • --quiet 会抑制 mongosh 连接信息

  • --eval 调用 find 方法

  • .forEach 是一个JavaScript方法,它告诉 mongosh 遍历响应

  • EJSON.stringify() 将每个文档转换为JSON

输出是

{"_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"}}

单行输出格式方便用于脚本。 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 ) ) )"

输出是

# 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 是在 .forEach() 的每次迭代中由 EJSON.stringify() 转换的BSON值。

  • null 是一个可选的 replacer 的占位符。当 replacer 不存在时,EJSON.stringify() 返回所有具有定义值的字段。

  • 3spacer 值。它告诉 EJSON.stringify() 每个新级别缩进3个空格。

如果您希望输出字符串包含额外的类型信息,请添加 { 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 } ) \
) )"

输出是

# Note: This is only the first document.
{
"_id": {
"$oid": "64da90c1175f5091debcab26"
},
"custId": {
"$numberInt": "345"
},
"purchaseDate": {
"$date": {
"$numberLong": "1688428800000"
}
},
"quantity": {
"$numberInt": "4"
},
"cost": {
"$numberDecimal": "100.60"
}
}

EJSON.stringify() 提供了格式化选项,减少了使用如 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 \
);"

输出是

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

mongosh 命令行返回的输出与旧版 mongo 命令行不同。如果你有需要以类似旧版 mongo 命令行格式化输出的脚本,请尝试使用 EJSON.stringify().

mongoshmongo 中运行一个示例查询,以查看不同的格式。

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

旧版输出

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

mongosh 输出

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

使用 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"}}]

返回

serialize()