【问题标题】:Find by the first characters of a string with a variable mongodb, nodejs通过带有变量mongodb,nodejs的字符串的第一个字符查找
【发布时间】:2022-02-10 21:47:37
【问题描述】:

我想通过第一个字符在我的 mongodb 数据库中找到一个文档。

我的文档中有这样一个字符串:

name: 'Georges'

此名称是之前生成的,但它可能太长,直到 16MB! 所以它太长了,无法在 16 MB 的字符串上进行查找。 所以我在变量中有名字

var name = 'Georges'

我在我的数据库中插入。我想用角色找到它。 例如:

  var query = {name: /^Geo/};
  res = await db.collection('people').find(query).toArray());

它的工作原理就是这样,但我想要这个:

var first = 'Geo';
var query = {name: /^first/};
res = await db.collection('people').find(query).toArray());

但它不能工作,因为它是一个变量,而不是一个字符串。

提前致谢

【问题讨论】:

    标签: node.js mongodb find var


    【解决方案1】:

    使用RegExp

    var first = 'Geo';
    var regex = new RegExp("^" + first, "g");
    var query = {name: regex};
    

    【讨论】:

      猜你喜欢
      • 2018-01-19
      • 2020-02-14
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多