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

$toObjectId ( 表达式操作符 )

$toObjectId

将值转换为 ObjectId()。如果该值无法转换为 ObjectId,则 $toObjectId 会出错。如果值为 null 或丢失,则 $toObjectId 将返回 null。

$toObjectId 通过以下语法实现:

{ $toObjectId: <expression>}

$toObjectId 采用任何有效的表达式。

$toObjectId 是以下 $convert 表达式的简写:

{ $convert: { input: <expression>, to: "objectId" } }

提示

$convert

下表列出可以转换为对象标识符的输入类型:

输入类型
行为

字符串

以长度为 24 的 16 进制字符串返回对象标识符。

不能转换不是长度 24 的十六进制字符串的字符串值。

下表列出了转换为日期的部分示例:

例子
结果

{$toObjectId: "5ab9cbfa31c2ab715d42129e"}

ObjectId("5ab9cbfa31c2ab715d42129e")

{$toObjectId: "5ab9cbfa31c2ab715d42129"}

错误

使用以下文档创建集合 orders:

db.orders.insertMany( [ { _id: "5ab9cbe531c2ab715d42129a", item: "apple", qty: 10 }, { _id: ObjectId("5ab9d0b831c2ab715d4212a8"), item: "pie", qty: 5 }, { _id: ObjectId("5ab9d2d331c2ab715d4212b3"), item: "ice cream", qty: 20 }, { _id: "5ab9e16431c2ab715d4212b4", item: "almonds", qty: 50 },] )

orders 集合上的以下聚合操作会在按值排序之前将 _id 转换为 ObjectId:

// Define stage to add convertedId field with converted _id value idConversionStage = { $addFields: { convertedId: { $toObjectId: "$_id" } }}; // Define stage to sort documents by the converted qty values sortStage = { $sort: { "convertedId": -1 }}; db.orders.aggregate( [ idConversionStage, sortStage] )

该操作将返回以下文档:

{ _id: '5ab9e16431c2ab715d4212b4', item: 'almonds', qty: 50, convertedId: ObjectId("5ab9e16431c2ab715d4212b4")},{ _id: ObjectId("5ab9d2d331c2ab715d4212b3"), item: 'ice cream', qty: 20, convertedId: ObjectId("5ab9d2d331c2ab715d4212b3")},{ _id: ObjectId("5ab9d0b831c2ab715d4212a8"), item: 'pie', qty: 5, convertedId: ObjectId("5ab9d0b831c2ab715d4212a8")},{ _id: '5ab9cbe531c2ab715d42129a', item: 'apple', qty: 10, convertedId: ObjectId("5ab9cbe531c2ab715d42129a")}

注意

如果转换操作遇到错误,聚合操作会停止并抛出错误。要覆盖此行为,请改为使用 $convert。

给本页内容打分

在此页面上