$toObjectId(聚合)
定义
$toObjectId
将值转换为
ObjectId()
。如果值不能转换为ObjectId,$toObjectId
将报错。如果值为null或不存在,$toObjectId
返回null。$toObjectId
的语法如下{ $toObjectId: <expression> } $toObjectId
可以接受任何有效的 表达式。$toObjectId
是以下$convert
表达式的简写{ $convert: { input: <expression>, to: "objectId" } }
行为
以下表格列出了可以转换为ObjectId的输入类型
输入类型 | 行为 |
---|---|
字符串 | 返回长度为24的十六进制字符串的ObjectId。 不能将不是长度为24的十六进制字符串的字符串值转换为ObjectId。 |
以下是一些转换为日期的示例
示例 | 结果 |
---|---|
{$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
代替。