javascript - 如何将多个分隔符传递到 mongodb 查询中的 $split 管道函数中?

标签 javascript python mongodb pymongo

我需要根据多个分隔符(即逗号、空格和点)分割字符串。 如何将其传递给 $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/

相关文章:

javascript - Bash 和 mongodb 脚本评估变量

javascript - Adobe DTM 和引用对象的时间

javascript - treeview 展开所有有 child 的元素

python - Jenkins 主/从窗口

MongoDB嵌套查询使用聚合函数

javascript - 在 Node JS 应用程序中实现单例 mongoDB DB 对象

javascript - Material-ui Button onClick() causes "Uncaught TypeError: Cannot read property ' name' of undefined"错误

javascript - jQuery/CSS 脚本根据一天中的时间更改按钮颜色

python - Python多处理图像压缩-100%时只有一个CPU

python - 无法使用 sasl python 模块构建 docker 镜像