$convert (aggregation)

在本页面

定义

$convert

版本4.0中的新功能。

将值转换为指定的类型。

$convert具有以下语法:

{
   $convert:
      {
         input: <expression>,
         to: <type expression>,
         onError: <expression>,  // Optional.
         onNull: <expression>    // Optional.
      }
}

$convert需要具有以下字段的文档:

$convert之外,当默认的“ onError”和“ onNull”行为可以接受时,MongoDB还提供以下聚合运算符作为速记:

  • $toBool

  • $toDate

  • $toDecimal

  • $toDouble

  • $toInt

  • $toLong

  • $toObjectId

  • $toString

行为

转换为布尔值

下表列出了可以转换为布尔值的输入类型:

下表列出了一些转换为布尔值的示例:

也可以看看

$toBool

转换为整数

下表列出了可以转换为整数的输入类型:

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

也可以看看

$toInt操作符。

转换为十进制

下表列出了可以转换为十进制的输入类型:

下表列出了一些转换为十进制的示例:

也可以看看

$toDecimal

转换为Double

下表列出了可以转换为双精度型的输入类型:

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

也可以看看

$toDouble

转换为Long

下表列出了可以转换为long的输入类型:

下表列出了一些到长示例的转换:

也可以看看

$toLong

转换为日期

下表列出了可以转换为日期的输入类型:

下表列出了一些转换日期的示例:

也可以看看

$toDate操作符, $dateFromString

转换成的ObjectId

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

下表列出了一些转换日期的示例:

也可以看看

$toObjectId操作符。

转换为字符串

下表列出了可以转换为字符串的输入类型:

下表列出了一些转换为字符串的示例:

也可以看看

$toString操作符。 $dateToString

例子

orders使用以下文档创建一个集合:

db.orders.insert( [
   { _id: 1, item: "apple", qty: 5, price: 10 },
   { _id: 2, item: "pie", qty: 10, price: NumberDecimal("20.0") },
   { _id: 3, item: "ice cream", qty: 2, price: "4.99" },
   { _id: 4, item: "almonds" },
   { _id: 5, item: "bananas", qty: 5000000000, price: NumberDecimal("1.25") }
] )

集合上的以下汇总操作orders会将转换price为小数:

// 定义使用转换后的价格和数量值添加convertedPrice和convertedQty字段的阶段
// 如果没有price或qty值,则返回十进制值或整数值
// 如果不能转换价格或数量值,将返回一个字符串

priceQtyConversionStage = {
   $addFields: {
      convertedPrice: { $convert: { input: "$price", to: "decimal", onError: "Error", onNull: NumberDecimal("0") } },
      convertedQty: { $convert: {
         input: "$qty", to: "int",
         onError:{$concat:["Could not convert ", {$toString:"$qty"}, " to type integer."]},
         onNull: NumberInt("0")
      } },
   }
};

totalPriceCalculationStage = {
   $project: { totalPrice: {
     $switch: {
        branches: [
          { case: { $eq: [ { $type: "$convertedPrice" }, "string" ] }, then: "NaN" },
          { case: { $eq: [ { $type: "$convertedQty" }, "string" ] }, then: "NaN" },
        ],
        default: { $multiply: [ "$convertedPrice", "$convertedQty" ] }
     }
} } };

db.orders.aggregate( [
   priceQtyConversionStage,
   totalPriceCalculationStage
])

该操作返回以下文档:

{ "_id" : 1, "totalPrice" : NumberDecimal("50.0000000000000") }
{ "_id" : 2, "totalPrice" : NumberDecimal("200.0") }
{ "_id" : 3, "totalPrice" : NumberDecimal("9.98") }
{ "_id" : 4, "totalPrice" : NumberDecimal("0") }
{ "_id" : 5, "totalPrice" : "NaN" }

译者:李冠飞

校对:

最后更新于