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")
}
相关推荐
JIngJaneIL7 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
晚风吹人醒.7 小时前
缓存中间件Redis安装及功能演示、企业案例
linux·数据库·redis·ubuntu·缓存·中间件
Y***98518 小时前
DVWA靶场通关——SQL Injection篇
数据库·sql
Yawesh_best8 小时前
告别系统壁垒!WSL+cpolar 让跨平台开发效率翻倍
运维·服务器·数据库·笔记·web安全
蒋士峰DBA修行之路8 小时前
实验二十八 SQL PATCH调优
数据库·sql·gaussdb
I***t7168 小时前
一条sql 在MySQL中是如何执行的
数据库·sql·mysql
一 乐8 小时前
应急知识学习|基于springboot+vue的应急知识学习系统(源码+数据库+文档)
数据库·vue.js·spring boot
微学AI10 小时前
内网穿透的应用-突破局域网束缚,MongoDB 远程访问使用cpolar原来可以这么简单
数据库·mongodb
大锦终11 小时前
【MySQL】内置函数
数据库·mysql
猿小喵11 小时前
索引优化-MySQL性能优化
数据库·mysql·性能优化