$toObjectId (aggregation)

On this page本页内容

Definition定义

$toObjectId

New in version 4.0.在版本4.0中新增

Converts a value to an ObjectId(). 将值转换为ObjectId()If the value cannot be converted to an ObjectId, $toObjectId errors. 如果值无法转换为ObjectId,则$toObjectId错误。If the value is null or missing, $toObjectId returns null.如果值为null或缺失,$toObjectId将返回null

$toObjectId has the following syntax:语法如下:

{
   $toObjectId: <expression>
}

The $toObjectId takes any valid expression.$toObjectId接受任何有效表达式。

The $toObjectId is a shorthand for the following $convert expression:$toObjectId是以下$convert表达式的缩写:

{ $convert: { input: <expression>, to: "objectId" } }
Tip提示
See also: 参阅:

Behavior行为

The following table lists the input types that can be converted to an ObjectId:下表列出了可以转换为ObjectId的输入类型:

Input Type输入类型Behavior行为
String

Returns an ObjectId for the hexadecimal string of length 24.返回长度为24的十六进制字符串的ObjectId。

You cannot convert a string value that is not a hexadecimal string of length 24.不能转换不是长度为24的十六进制字符串的字符串值。

The following table lists some conversion to date examples:下表列出了一些转换为日期的示例:

Example示例Results结果
{$toObjectId: "5ab9cbfa31c2ab715d42129e"}ObjectId("5ab9cbfa31c2ab715d42129e")
{$toObjectId: "5ab9cbfa31c2ab715d42129"}Error

Example示例

Create a collection orders with the following documents:使用以下文档创建集合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 },
] )

The following aggregation operation on the orders collection converts the _id to ObjectId before sorting by the value: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
] )

The operation returns the following documents:该操作返回以下文档:

{
  _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")
}
Note注意

If the conversion operation encounters an error, the aggregation operation stops and throws an error. 如果转换操作遇到错误,聚合操作将停止并抛出错误。To override this behavior, use $convert instead.要覆盖此行为,请改用$convert

←  $toLong (aggregation)$top (aggregation accumulator) →