Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

$toString(表达式操作符)

$toString

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

$toString 通过以下语法实现:

{
$toString: <expression>
}

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

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

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

提示

  • $convert

  • $dateToString

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

输入类型
行为

阵列

以字符串形式返回Array

8.3版本新增

BinData

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

布尔

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

Date

以字符串形式返回Date

Decimal 数据类型

Decimal以字符串形式返回 值。

double

Double以字符串形式返回 值。

整型

Integer以字符串形式返回 值。

Long

Long以字符串形式返回 值。

Max key

以字符串形式返回MaxKey

8.3版本新增

最小键值

以字符串形式返回MinKey

8.3版本新增

对象

以字符串形式返回该对象。

8.3版本新增

ObjectId

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

正则表达式

以字符串形式返回Regular Expression

8.3版本新增

字符串

无需操作。返回字符串值。

时间戳

以字符串形式返回Timestamp

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

在此页面上