Mongodb:如何使用 $susbtr 函数
您可以使用 MongoDB 中的$substr函数从字符串中提取子字符串。
该函数使用以下基本语法:
db.myCollection.aggregate([
{ $project : {substring: { $substr : [ " $fullstring ", 0, 4 ] }}}
])
此特定示例从位置 0 开始的标记为“fullString”的字段中提取所有四个字符。
以下示例展示了如何在具有以下文档的收藏销售实践中使用此语法:
db.sales.insertOne({yearMonth: 201702, amount: 40 })
db.sales.insertOne({yearMonth: 201802, amount: 32 })
db.sales.insertOne({yearMonth: 201806, amount: 19 })
db.sales.insertOne({yearMonth: 201910, amount: 29 })
db.sales.insertOne({yearMonth: 201907, amount: 35 })
示例:如何在 MongoDB 中使用 $susbtr 函数
我们可以使用以下代码从“yearMonth”字段中提取前四个字符并将它们显示在名为“year”的新字段中:
db.sales.aggregate([
{ $project : {year: { $substr : [ " $yearMonth ", 0, 4 ] }}}
])
此代码产生以下结果:
{ _id: ObjectId("620145544cb04b772fd7a929"), year: '2017' }
{ _id: ObjectId("620145544cb04b772fd7a92a"), year: '2018' }
{ _id: ObjectId("620145544cb04b772fd7a92b"), year: '2018' }
{ _id: ObjectId("620145544cb04b772fd7a92c"), year: '2019' }
{ _id: ObjectId("620145544cb04b772fd7a92d"), year: '2019' }
请注意,每个文档的“monthYear”字段的前四个字符显示在标记为“year”的新字段中。
需要注意的是,此代码仅显示子字符串。
要实际向包含此子字符串的集合添加新字段,我们需要使用$merge函数,如下所示:
db.sales.aggregate([
{ $project : {year: { $substr : [ " $yearMonth ", 0, 4 ] }}},
{ $merge : "sales" }
])
更新后的集合现在如下所示:
{ _id: ObjectId("620145544cb04b772fd7a929"),
yearMonth: 201702,
amount: 40,
year: '2017' }
{ _id: ObjectId("620145544cb04b772fd7a92a"),
yearMonth: 201802,
amount: 32,
year: '2018' }
{ _id: ObjectId("620145544cb04b772fd7a92b"),
yearMonth: 201806,
amount: 19,
year: '2018' }
{ _id: ObjectId("620145544cb04b772fd7a92c"),
yearMonth: 201910,
amount: 29,
year: '2019' }
{ _id: ObjectId("620145544cb04b772fd7a92d"),
yearMonth: 201907,
amount: 35,
year: '2019' }
请注意,标题为“year”的新字段已添加到集合中的每个文档中,并且它显示“yearMonth”字段的前四个字符。
注意:您可以在此处找到$substr函数的完整文档。
其他资源
以下教程解释了如何在 MongoDB 中执行其他常见操作: