【问题标题】:How to search character by character in mongodb array text field?如何在mongodb数组文本字段中逐个字符搜索?
【发布时间】:2018-11-05 12:43:56
【问题描述】:

我在 mongodb 中的文档是这样的:

[{
  "_id" : 1,
  "name" : "Himanshu",
  "tags" : ["member", "active"]
},{
  "_id" : 2,
  "name" : "Teotia",
  "tags" : ["employer", "withdrawal"]
},{ 
  "_id" : 3,
  "name" : "John",
  "tags" : ["member", "deactive"]
},{
  "_id" : 4,
  "name" : "Haris",
  "tags" : ["employer", "action"]
}]
  1. 我想在这里搜索的是,如果我们有像 {"tags" : ["member", "act"]} 这样的过滤器数组,它将回复 id 的 12,因为这里的 member 是完全匹配的,act 是两个文档中的部分匹配。
  2. 如果我有像{"tags" : ["mem"] } 这样的过滤器,那么它应该回复id 的13
  3. 另一种情况如果我有像{"tags" : ["member", "active"]} 这样的过滤器,那么它应该只回答1

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    这里基本上需要两个概念。

    1. 将数组的每个输入字符串转换为锚定到字符串“开始”的正则表达式:

    2. 使用$all 运算符应用列表以确保“全部”匹配:

      var filter = { "tags": [ "mem", "active" ] };
      
      // Map with regular expressions
      filter.tags = { "$all": filter.tags.map(t => new RegExpr("^" + t)) };
      // makes filter to { "tags": { "$all": [ /^mem/, /^active/ ] } }
      
      // search for results
      db.collection.find(filter);
      

    【讨论】:

    • 必须是RegExp 而不是RegExpr
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多