MongoDB BSON 展开对象

基本方法

1. 使用 printjson 函数

默认情况下会自动对 JSON 对象进行一定程度的格式化和展开

javascript 复制代码
// 基本使用
printjson(myObject);

2. 调整 DBQuery.shellBatchSize

javascript 复制代码
// 增加显示的文档数量
DBQuery.shellBatchSize = 100;  // 默认为20

完全展开嵌套对象

1. 使用 JSON.stringify 自定义格式化

javascript 复制代码
// 完全展开所有嵌套对象,使用2个空格缩进
print(JSON.stringify(myObject, null, 2));

2. 使用自定义函数展开特定深度

javascript 复制代码
function expandJson(obj, depth) {
  return JSON.stringify(obj, null, depth || 2);
}

// 使用
print(expandJson(myObject, 4));  // 使用4个空格缩进

3. MongoDB 5.0+ 中的 pretty() 方法

javascript 复制代码
// 对查询结果进行格式化
db.collection.find().pretty();

在 mongosh 中控制输出格式

如果你使用的是新版 MongoDB Shell (mongosh),它提供了更多控制输出格式的选项:

javascript 复制代码
// 设置输出格式
config.set("displayMode", "expanded");  // 完全展开
config.set("displayMode", "compact");   // 紧凑模式

注意事项

  • 对于非常大的文档,完全展开可能会导致输出非常长,可能难以在控制台阅读
  • 使用 JSON.stringify 可能会丢失 MongoDB 特定类型信息(如 ObjectId)

希望这些方法能帮助你有效地展开和查看 MongoDB 中的 JSON 文档。

相关推荐
bing_1581 小时前
Spring Boot 中 MongoDB @DBRef注解适用什么场景?
spring boot·后端·mongodb
Austindatabases2 小时前
给阿里云MongoDB 的感谢信 !!成本降低80%
数据库·mongodb·阿里云·云计算
bing_1584 小时前
Spring Boot 中如何启用 MongoDB 事务
spring boot·后端·mongodb
大数据魔法师4 小时前
MongoDB(六) - Studio 3T 基本使用教程
mongodb·nosql
micromicrofat1 天前
mongodb升级、改单节点模式
数据库·mongodb
卓越进步1 天前
1、mongodb-- BSON 学习和JSON性能对比
学习·mongodb·json
三流搬砖艺术家2 天前
Windows 下 MongoDB 安装指南
数据库·mongodb
席万里2 天前
MongoDB入门详解
数据库·mongodb
bing_1583 天前
在Spring Boot 中如何配置MongoDB的副本集 (Replica Set) 或分片集群 (Sharded Cluster)?
spring boot·后端·mongodb
Python私教3 天前
Spring Boot操作MongoDB的完整示例大全
spring boot·后端·mongodb