Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

$toObjectId(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$toObjectId

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

$toObjectId 通过以下语法实现:

{
$toObjectId: <expression>
}

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

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

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

提示

另请参阅:

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

输入类型
行为
字符串

以长度为 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

← $toLong(聚合)

在此页面上