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")
}
相关推荐
qq_529835351 小时前
对计算机中缓存的理解和使用Redis作为缓存
数据库·redis·缓存
月光水岸New3 小时前
Ubuntu 中建的mysql数据库使用Navicat for MySQL连接不上
数据库·mysql·ubuntu
狄加山6753 小时前
数据库基础1
数据库
我爱松子鱼3 小时前
mysql之规则优化器RBO
数据库·mysql
chengooooooo4 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
Rverdoser5 小时前
【SQL】多表查询案例
数据库·sql
Galeoto5 小时前
how to export a table in sqlite, and import into another
数据库·sqlite
人间打气筒(Ada)5 小时前
MySQL主从架构
服务器·数据库·mysql
leegong231115 小时前
学习PostgreSQL专家认证
数据库·学习·postgresql
喝醉酒的小白5 小时前
PostgreSQL:更新字段慢
数据库·postgresql