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 variablemyObjectId.ObjectId()并将其存储在变量myObjectId中。Creates a string representation of使用myObjectIdusing thetoString()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