Database Manual / Reference / mongosh Methods / Object Constructors

ObjectId.toString() (mongosh method方法)

ObjectId.toString()
Returns the string representation of the ObjectId().返回ObjectId()的字符串表示形式。

Compatibility兼容性

You can use ObjectId.toString() for deployments hosted in the following environments:您可以将ObjectId.toString()用于在以下环境中托管的部署:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Example示例

The following example:以下示例:

  • Generates a new ObjectId() and stores it in the variable myObjectId.生成一个新的ObjectId()并将其存储在变量myObjectId中。
  • Creates a string representation of myObjectId using the toString() method.使用toString()方法创建myObjectId的字符串表示形式。
  • Stores the string representation in the variable myObjectIdString.将字符串表示存储在变量myObjectIdString中。

Run the following commands in mongosh:mongosh中运行以下命令:

myObjectId = ObjectId("507c7f79bcf86cd7994f6c0e")
myObjectIdString = myObjectId.toString()

The operation returns the following string:该操作返回以下字符串:

507c7f79bcf86cd7994f6c0e

To confirm the type of myObjectIdString, use the typeof JavaScript operator:要确认myObjectIdString的类型,请使用JavaScript运算符typeof

typeof myObjectIdString

The operation returns the following:该操作返回以下内容:

string