MongoDB 字符串截取 $substr


$substr,$substrBytes,$substrCP是aggregate的管道操作符,主要可用在project中,
$substr在版本3.4后最好使用$substrBytes

substr

db.getCollection("table_name").aggregate({ $project: { "new_string": { $substr: [< string > , < start > , < length > ] } } }) 

其中< string >是需截取的字符串,若為表內字段可用$加字段名。
< start >截取開始的位置,為整數,整數從0開始。若數字為負數或大於< string >的長度,則返回空字符串""。
< length >截取字符串長度,為整數。若數字為負數則返回< start >后的全部的字符串。

substrBytes

db.getCollection("table_name").aggregate({ $project: { "new_string": { $substrBytes : [< string expression >,< byte index >,< byte count >] } } }) 

其中< string expression >是需截取的字符串,若為表內字段可用$加字段名。
< byte index >截取開始的位置,為整數,整數從0開始。若數字為負數或大於< string >的長度,則返回空字符串""。
< byte count >截取字符串長度,為整數。若數字為負數則返回< start >后的全部的字符串。

substrCP

db.getCollection("table_name").aggregate({ $project: { "new_string": { $substrCP:[< string expression >,< code point index >,< code point count >] } } }) 

其中< string expression >是需截取的字符串,若為表內字段可用$加字段名。
< code point index >截取開始的位置,為整數,整數從0開始。若數字為負數或大於< string >的長度,則返回空字符串""。
< code point count >截取字符串長度,為整數。若數字為負數則返回< start >后的全部的字符串。

示例:

1.截取字符串
$substr$substrBytes結果相同,會將漢字的字符長度視為2。
$substrCP將漢字的字符長度視為1。

 
截取字符串

 

2.截取字段內容

截取字段內容


作者:滄海2122537190
鏈接:https://www.jianshu.com/p/8aa8794101e3
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM