MongoDB $substr 从索引到索引
MongoDB $substr from index to index
数据如"abc abc abc (xyz) efg efg".
我正在尝试从字符串中提取 xyz。
尝试在 $project 部分执行此操作:
$project: {
bracketextract : { $substr: [ "$title",{ $indexOfCP: [ "$title", "(" ]}, { $indexOfCP: [ "$title", ")" ]} - { $indexOfCP: [ "$title", "(" ]} ]},
}
你应该使用 $subtract to the length (you're using -
currently) and there should be 1
$add-ed 到起点
db.col.aggregate([
{
$project: {
bracketextract : { $substr: [ "$title", { $add: [ { $indexOfCP: [ "$title", "(" ]}, 1 ] } , { $subtract: [ { $indexOfCP: [ "$title", ")" ]}, { $add: [ { $indexOfCP: [ "$title", "(" ]}, 1 ] } ] } ]},
}
}
])
使用 $let 的可读性更高:
db.col.aggregate([
{
$project: {
bracketextract: {
$let: {
vars: {
start: { $add: [ { $indexOfCP: [ "$title", "(" ] }, 1 ] },
end: { $indexOfCP: [ "$title", ")" ] }
},
in: { $substr: [ "$title", "$$start", { $subtract: [ "$$end", "$$start" ] } ] }
}
}
}
}
])
数据如"abc abc abc (xyz) efg efg".
我正在尝试从字符串中提取 xyz。
尝试在 $project 部分执行此操作:
$project: {
bracketextract : { $substr: [ "$title",{ $indexOfCP: [ "$title", "(" ]}, { $indexOfCP: [ "$title", ")" ]} - { $indexOfCP: [ "$title", "(" ]} ]},
}
你应该使用 $subtract to the length (you're using -
currently) and there should be 1
$add-ed 到起点
db.col.aggregate([
{
$project: {
bracketextract : { $substr: [ "$title", { $add: [ { $indexOfCP: [ "$title", "(" ]}, 1 ] } , { $subtract: [ { $indexOfCP: [ "$title", ")" ]}, { $add: [ { $indexOfCP: [ "$title", "(" ]}, 1 ] } ] } ]},
}
}
])
使用 $let 的可读性更高:
db.col.aggregate([
{
$project: {
bracketextract: {
$let: {
vars: {
start: { $add: [ { $indexOfCP: [ "$title", "(" ] }, 1 ] },
end: { $indexOfCP: [ "$title", ")" ] }
},
in: { $substr: [ "$title", "$$start", { $subtract: [ "$$end", "$$start" ] } ] }
}
}
}
}
])