Docs 菜单
Docs 主页
/ /

$toString(表达式操作符)

$toString

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

$toString 通过以下语法实现:

{
$toString: <expression>
}

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

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

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

提示

  • $convert

  • $dateToString

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

输入类型
行为

阵列

Returns the Array as a string.

8.3版本新增

BinData

如果 BinData 是 UUID,则以 string 形式返回该 UUID。否则,返回以 base64 编码的 string 值。

布尔

以字符串形式返回该布尔值。

Date

Returns the Date as a string.

Decimal 数据类型

以 string 形式返回 Decimal 值。

double

以 string 形式返回 Double 值。

整型

以 string 形式返回 Integer 值。

Long

以 string 形式返回 Long 值。

Max key

Returns the MaxKey as a string.

8.3版本新增

最小键值

Returns the MinKey as a string.

8.3版本新增

对象

以 string 形式返回该对象。

8.3版本新增

ObjectId

以十六进制字符串形式返回 ObjectId 值。

正则表达式

Returns the Regular Expression as a string.

8.3版本新增

字符串

无需操作。返回 string 值。

时间戳

Returns the Timestamp as a string.

8.3版本新增

提示

要转换 10 以外的字符串,请使用 $convertbase 选项。

下表列出了转换为字符串的部分示例:

例子
结果

{ $toString: true }

"true"

{ $toString: false }

"false"

{ $toString: 2.5 }

"2.5"

{ $toString: Int32(2) }

"2"

{ $toString: Long(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"

{ $toString: /^ABC/i }

"/^ABC/i"

8.3版本新增

{ $toString: new Timestamp(1565545664, 1) }

"Timestamp(1565545664, 1)"

8.3版本新增

{ $toString: [["pizza", {type: "cheese"}]] }

"[\"pizza\",{\"type\":\"cheese\"}]"

8.3版本新增

{ $toString: {pizza: {type: "cheese"}} }

"{\"pizza\":{\"type\":\"cheese\"}}"

8.3版本新增

{ $toString: MinKey }

"MinKey"

8.3版本新增

{ $toString: MaxKey }

"MaxKey"

8.3版本新增

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

在此页面上