【问题标题】:how to find all documents with only looking at first letter of the values in mongoose如何仅查看猫鼬中值的第一个字母来查找所有文档
【发布时间】:2017-06-09 17:53:43
【问题描述】:

我想按第一个字母查找所有文档。

情况是当我在 mysql 中查询然后我可以做WHERE Stores LIKE 'a%'

the result would be all data with the first letter a.

问题是:

  • 如何使用mongoose 制作相同的query
  • case-sensitiveeg: (a,A) 怎么样。是否是同一个查询?
  • 是否需要为这种情况创建lowercase_field

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema mongoose-populate


    【解决方案1】:

    有一个$regex 运算符用于此目的,查询将如下所示:

    Model.find({"name": {$regex: /^a/, $options: 'i'}}).exec(callback);
    

    可以简化为:

    Model.find({"name": /^a/i}}).exec(callback);
    

    如果您需要在查询中传递变量:

    var char = 'a';
    Model.find({"name": {$regex: '^' + char, $options: 'i'}}).exec(callback);
    

    【讨论】:

    • 我是正则表达式的新手,如何在其中传递变量? $regex: /^variable/
    • 在我的例子中像这样工作:Model.find({"name": {$regex: '^' + char, $options: 'i'}}).exec(callback);
    猜你喜欢
    • 2021-05-11
    • 2013-10-21
    • 1970-01-01
    • 2022-01-17
    • 2014-02-03
    • 1970-01-01
    • 2020-07-25
    • 2022-12-10
    • 2014-02-17
    相关资源
    最近更新 更多