MongoDB聚合运算符:$toObjectId

MongoDB聚合运算符:$toObjectId

文章目录

  • [MongoDB聚合运算符:toObjectId](#MongoDB聚合运算符:toObjectId)

$toObjectId聚合运算符将指定的值转换为ObjectId。如果值无法被转换为ObjectId,则报错。

语法

js 复制代码
{
   $toObjectId: <expression>
}

$toObjectId接受任何有效的表达式。

$toObjectId$convert表达式的简写形式:

js 复制代码
{ $convert: { input: <expression>, to: "objectId" } }

使用

下表列出了可转换为ObjectId的类型:

输入类型 规则
String 返回长度为 24 的十六进制字符串的 ObjectId。如果字符串值不是长度为 24 的十六进制字符串,则无法转换。

下表列出了一些转换为ObjectId的示例:

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

举例

使用下面的脚本创建orders集合:

js 复制代码
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 },
] )

下面的聚合操将_id转换为ObjectId,并进行排序:

js 复制代码
// 定义转换阶段,将_id值转换为ObjectId并添加到文档

idConversionStage = {
   $addFields: {
      convertedId: { $toObjectId: "$_id" }
   }
};

// 定义排序阶段,根据convertedId进行排序


sortStage = {
   $sort: { "convertedId": -1 }
};


db.orders.aggregate( [
   idConversionStage,
   sortStage
] )

执行的结果为:

js 复制代码
{
  _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")
}
相关推荐
小高Baby@6 分钟前
解决幻读问题
数据库·mysql
TDengine (老段)9 分钟前
TDengine 转化函数 TO_TIMESTAMP 用户手册
java·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
java叶新东老师30 分钟前
CMakelists.txt 实现多级目录编译
java·服务器·数据库
Sean_summer33 分钟前
暑期第二周
前端·数据库·python
whn19771 小时前
达梦有多少个模式
数据库
王柏龙1 小时前
Entity Framework Core (EF Core) 中Database
数据库·microsoft
时序数据说1 小时前
时序数据库IoTDB的优势场景分析
大数据·数据库·物联网·时序数据库·iotdb
是阿建吖!1 小时前
【Redis】初识Redis(定义、特征、使用场景)
数据库·redis·缓存
Leo.yuan1 小时前
数据处理工具是做什么的?常见数据处理方法介绍
大数据·数据库·人工智能·python·信息可视化
旧时光巷2 小时前
SQL基础⑫ | 视图篇
数据库·sql·学习·mysql·oracle·视图