文档菜单
文档首页
/
MongoDB 手册
/ / /

转换为字符串(聚合)

在本页面上

  • 定义
  • 行为
  • 示例
$toString

将值转换为字符串。如果值不能转换为字符串,$toString 将产生错误。如果值为null或不存在,$toString 返回null。

$toString 具有以下语法

{
$toString: <expression>
}

$toString 接受任何有效的表达式.

$toString 是以下 $convert 表达式的简写

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

提示

另请参阅

  • $convert

  • $dateToString

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

输入类型
行为
BinData
返回二进制数据值作为字符串。
Boolean
返回布尔值作为字符串。
Double
返回双精度值作为字符串。
Decimal
返回十进制值作为字符串。
Integer
返回整数值作为字符串。
Long
返回长整数值作为字符串。
ObjectId
返回ObjectId值作为十六进制字符串。
String
无操作。返回字符串值。
Date
返回日期作为字符串。

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

示例
结果
{$toString: true}
"true"
{$toString: false}
"false"
{$toString: 2.5}
"2.5"
{$toString: NumberInt(2)}
"2"
{$toString: NumberLong(1000)}
"1000"
{$toString: ObjectId("5ab9c3da31c2ab715d421285")}
"5ab9c3da31c2ab715d421285"
{$toString: ISODate("2018-03-27T16:58:51.538Z")}
"2018-03-27T16:58:51.538Z"
{ $toString: BinData(4, "hn3f") }
"hn3f"

创建一个包含以下文档的集合 orders

db.orders.insertMany( [
{ _id: 1, item: "apple", qty: 5, zipcode: 93445 },
{ _id: 2, item: "almonds", qty: 2, zipcode: "12345-0030" },
{ _id: 3, item: "peaches", qty: 5, zipcode: 12345 },
] )

orders 集合上执行以下聚合操作将 zipcode 转换为字符串,然后按字符串值排序

// Define stage to add convertedZipCode field with the converted zipcode value
zipConversionStage = {
$addFields: {
convertedZipCode: { $toString: "$zipcode" }
}
};
// Define stage to sort documents by the converted zipcode
sortStage = {
$sort: { "convertedZipCode": 1 }
};
db.orders.aggregate( [
zipConversionStage,
sortStage
] )

操作返回以下文档

{
_id: 3,
item: 'peaches',
qty: 5,
zipcode: 12345,
convertedZipCode: '12345'
},
{
_id: 2,
item: 'almonds',
qty: 2,
zipcode: '12345-0030',
convertedZipCode: '12345-0030'
},
{
_id: 1,
item: 'apple',
qty: 5,
zipcode: 93445,
convertedZipCode: '93445'
}

注意

如果在转换操作中遇到错误,聚合操作将停止并抛出错误。要覆盖此行为,请使用 $convert 代替。

返回

topN

在本页面上