$toObjectId (aggregation)
On this page本页内容
Definition定义
$toObjectId-
Converts a value to an将值转换为ObjectId().ObjectId()。If the value cannot be converted to an ObjectId,如果无法将值转换为ObjectId,则$toObjectIderrors.$toObjectId将出错。If the value is null or missing,如果该值为$toObjectIdreturns null.null或缺失,$toObjectId将返回null。$toObjectIdhas the following syntax:具有以下语法:{
$toObjectId: <expression>
}The$toObjectIdtakes any valid expression.$toObjectId采用任何有效的表达式。The$toObjectIdis a shorthand for the following$convertexpression:$toObjectId是以下$convert表达式的简写:{ $convert: { input: <expression>, to: "objectId" } }TipSee also:另请参阅:
Behavior行为
The following table lists the input types that can be converted to an ObjectId:下表列出了可以转换为ObjectId的输入类型:
| String |
The following table lists some conversion to date examples:下表列出了一些转换到日期的示例:
{$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")
}