对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

写入自定义日志条目

您可以从 MongoDB Shell脚本 写入自定义 日志条目 。自定义日志条目有助于调试和错误处理,并在脚本执行特定功能时向您警报。

MongoDB Shell支持以下自定义日志条目的方法:

  • log.debug()

  • log.error()

  • log.fatal()

  • log.info()

  • log.warn()

1

以下脚本将文档插入 movies集合并写入自定义 info日志条目。如果脚本出错,则会改为写入自定义 error日志条目。

// connect-and-insert-with-log-entry.js try { db = connect( 'mongodb://localhost/myDatabase' ); db.movies.insertMany( [ { title: 'Titanic', year: 1997, genres: [ 'Drama', 'Romance' ] }, { title: 'Spirited Away', year: 2001, genres: [ 'Animation', 'Adventure', 'Family' ] }, { title: 'Casablanca', genres: [ 'Drama', 'Romance', 'War' ] } ] ) log.info('InsertData: Inserted 3 movies');} catch (error) { log.error('Insert failed', { error: error.message });}

将脚本保存为 connect-and-insert-with-log-entry.js。

2

要运行connect-and-insert-with-log-entry.js脚本,请使用 mongosh 连接到您的部署并在MongoDB Shell中运行以下命令:

load("connect-and-insert-with-log-entry.js")

或者,您可以在启动 mongosh 时使用 --file 选项以编程方式运行脚本:

mongosh --file connect-and-insert-with-log-entry.js

自定义日志条目将显示在会话日志中:

{"t":{"$date":"2025-02-25T18:04:01.690Z"},"s":"I","c":"MONGOSH-SCRIPTS","id":1000000054,"ctx":"custom-log","msg":"InsertData: Inserted 3 movies"}

有关日志会话以及如何检索日志消息的更多信息,请参阅查看Shell日志。

要验证脚本是否已插入文档,查询movies集合:

use myDatabasedb.movies.find()

输出:

[ { _id: ObjectId('67bde8c2a527c6b1341979f2'), title: 'Titanic', year: 1997, genres: [ 'Drama', 'Romance' ] }, { _id: ObjectId('67bde8c2a527c6b1341979f3'), title: 'Spirited Away', year: 2001, genres: [ 'Animation', 'Adventure', 'Family' ] }, { _id: ObjectId('67bde8c2a527c6b1341979f4'), title: 'Casablanca', genres: [ 'Drama', 'Romance', 'War' ] }]
给本页内容打分