【问题标题】:How to combine Mongo DB variables with wildcard characters如何将 Mongo DB 变量与通配符结合起来
【发布时间】:2021-10-24 06:18:30
【问题描述】:

我想用一个变量参数化一些查询。所以选择字段key中具有特定子字符串的所有文档

以下是工作代码:

db.getCollection('df_FI').find({
  $and: 
    [
      {key:{"$in":[/2021-08-01_2021-08-11_Reported/]}}
    ]
}) 

这需要应用于许多查询,所以我想要一个变量/常量来替换字符串。以下是失败的。如何将变量与通配符结合起来?

key_sub_string = "2021-08-01_2021-08-11_Reported";
db.getCollection('df_FI').find({
  $and: 
    [
      {key:{"$in":["/" + key_sub_string + "/"]}}
    ]
}) 

【问题讨论】:

  • 您是在 CLI 中执行 MongoDB 查询还是在执行一些后端查询?
  • 在 NoSQLBooster 中运行
  • 刚刚用 deleteMany 试过了。我得到“$regex is not defined”,我需要添加声明吗?
  • 尝试把$regex放在""中,比如"$regex"
  • 成功了! Tks key_sub_string = "2020-06-01_2020-06-10_Reported" db.df_FI.remove({"key" : { $regex : key_sub_string}})

标签: sql mongodb mongodb-query


【解决方案1】:

你不需要$and,因为你只有一个表达式。您可以使用$regex 检查某些key 是否有子字符串:

db.collection.find({key : {$regex : substring}});

下面是工作示例:https://mongoplayground.net/p/fBlO04PdVXH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2021-06-10
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多