MongoDB聚合运算符:$toObjectId

MongoDB聚合运算符:$toObjectId


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

语法

{
   $toObjectId: <expression>
}

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

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

{ $convert: { input: <expression>, to: "objectId" } }

使用

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

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

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

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

举例

使用下面的脚本创建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 },
] )

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

// 定义转换阶段,将_id值转换为ObjectId并添加到文档

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

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


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


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

执行的结果为:

{
  _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")
}
  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值