You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB中使用pretty()格式化查询结果失败求助

MongoDB查询结果未按.pretty()格式化的解决办法

针对你遇到的.pretty()方法未生效的问题,可尝试以下几种解决方式:

方法1:强制开启shell格式化输出

在MongoDB Shell中先执行以下命令,再重新运行查询:

DBQuery.prototype._prettyShell = true;
db.bookshop.find(
  {"BOOK.topic":"Computer Science", "BOOK.price":{$gt:70}},
  {"BOOK.isbn":1, "BOOK.title":1, _id:0}
).pretty();

这条命令会强制Shell对查询结果进行格式化,嵌套文档也能展开显示。

方法2:使用shell配置命令(MongoDB 4.2+适用)

如果你的MongoDB版本是4.2及以上,可直接设置Shell输出格式:

set shellPretty true
db.bookshop.find(
  {"BOOK.topic":"Computer Science", "BOOK.price":{$gt:70}},
  {"BOOK.isbn":1, "BOOK.title":1, _id:0}
).pretty();

方法3:用JSON.stringify手动格式化

如果以上方法都不生效,可借助JSON.stringify手动控制输出格式:

db.bookshop.find(
  {"BOOK.topic":"Computer Science", "BOOK.price":{$gt:70}},
  {"BOOK.isbn":1, "BOOK.title":1, _id:0}
).forEach(doc => {
  print(JSON.stringify(doc, null, 4));
});

这里的4代表缩进空格数,可根据需求调整。

内容的提问来源于stack exchange,提问作者user12062753

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:50:00