Docs 菜单
Docs 主页
/
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
数组或函数
Optional

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

replacer 可以是数组或函数。

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

一个带有两个参数的函数: keyvaluekey提供函数的this上下文。 EJSON 返回转换后的value

该函数针对每个对象运行。对象值将替换为函数的返回值。

有关示例,请参阅使用函数转换输出字段。

spacer
整数或字符串
Optional

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

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

其他配置选项

选项
默认
含义
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() 每个文档级别缩进 5 个空格。

{
"_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值都会乘以 2。 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 )
)

该示例查询sales集合的 7 月2023销售额。

  • 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"
}
}
  • oEJSON.stringify().forEach()的每次迭代时转换的 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 Shell 返回的输出与旧版mongo Shell 不同。如果您的脚本要求输出格式与传统mongo Shell 类似,请尝试使用EJSON.stringify()重新格式化mongosh输出。

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()