MongoDB聚合运算符:$replaceAll
文章目录
$replaceAll
聚合运算在输入的字符串中搜索目标字符串,并使用指定的字符串替换所有找到的目标字符串。如果没有找到目标字符串,则返回输入字符串。
$replaceAll
既区分大小写又区分变音符号,并且忽略集合中存在的任何排序规则。
语法
{
$replaceAll: {
input: <expression>, find: <expression>, replacement: <expression> } }
参数字段说明
input
:输入的字符串,可以是任何可被解析为字符串的表达式,如果表达式解析为null
或引用的字段不存在,$replaceAll
返回null
。find
:要搜索的字符串,可以是任何可被解析为字符串的表达式,如果表达式解析为null
或引用的字段不存在,$replaceAll
返回null
。replacement
:要替换的的字符串,可以是任何可被解析为字符串或null
的表达式。
使用
input
、find
和replacement
表达式的计算结果必须为字符串或 null
,否则 $replaceAll
将失败并出现错误。。
$replaceAll 与 Null
如果 input
或 find
引用的字段字段不存在,则返回 null
。
如果 input
、find
或 replacement
中的任何一个计算结果为 null
,则整个 $replaceAll
表达式计算结果为 null
:
例如 | 结果 |
---|---|
{ $replaceAll: { input: null, find: "abc", replacement: "ABC" } } |
null |
{ $replaceAll: { input: "abc", find: null, replacement: "ABC" } } |
null |
{ $replaceAll: { input: "abc", find: "abc", replacement: null } } |
null |
$replaceAll 和排序规则
所有 $replaceAll
表达式的字符串匹配始终区分大小写和变音符号。使用 $replaceAll
执行字符串比较时,在集合、db.collection.aggregate)
或索引上配置的任何排序规则都将被忽略。
例如,创建一个排序规则强度为 1 的示例集合:
db.createCollection( "myColl", {
collation: {