Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

$toString(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$toString

将值转换为字符串。如果该值无法转换为字符串,则 $toString出错。如果值为 null 或缺失,则$toString返回 null。

$toString 通过以下语法实现:

{
$toString: <expression>
}

$toString可采用任何有效的表达式。

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

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

提示

另请参阅:

  • $convert

  • $dateToString

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

输入类型
行为
布尔
以字符串形式返回该布尔值。
double
以字符串形式返回该 double 值。
Decimal 数据类型
以字符串形式返回该十进制值。
整型
以字符串形式返回该整型值。
Long
以字符串形式返回该长整型值。
ObjectId
以十六进制字符串形式返回该 ObjectId 值。
字符串
不操作。返回该字符串值。
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"

使用以下文档创建集合 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

在此页面上