我需要根据多个分隔符(即逗号、空格和点)分割字符串。 如何将其传递给 $split 函数?
我在第二个参数中尝试了“|.|,”,但没有成功。
集合结构示例:
[
{
"foo": "i like product 1",
},
{
"foo": "product 3, is bad",
},
]
//我尝试过的查询:
db.collection.aggregate([
{
$project: {
words: {
$split: [
"$foo",
" |.|,"
]
}
}
},
{
$unwind: {
path: "$words"
}
},
{
$group: {
_id: "$words",
count: {
$sum: 1
}
}
}
])
最佳答案
您不能将正则表达式作为 $split 中的分隔符传递。看看https://docs.mongodb.com/manual/reference/operator/aggregation/split/ .
如果“foo”遵循英语规则,即空格后跟逗号和句号,那么以下查询将适合您。我们在空白处分割单词,并从每个单词中删除逗号和句号。
db.collection.aggregate([
{
$project:{
"words":{
$split:["$foo"," "]
}
}
},
{
$project:{
"words":{
$map:{
"input":"$words",
"as":"word",
"in":{
$trim:{
"input": "$$word",
"chars": " .,"
}
}
}
}
}
},
{
$unwind:"$words"
},
{
$group:{
"_id":"$words",
"word":{
$first:"$words"
},
"count":{
$sum:1
}
}
},
{
$project:{
"_id":0
}
}
]).pretty()
结果:
{ "word" : "bad", "count" : 1 }
{ "word" : "is", "count" : 1 }
{ "word" : "i", "count" : 1 }
{ "word" : "product", "count" : 2 }
{ "word" : "like", "count" : 1 }
{ "word" : "3", "count" : 1 }
{ "word" : "1", "count" : 1 }
关于javascript - 如何将多个分隔符传递到 mongodb 查询中的 $split 管道函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57297270/