首页 > 解决方案 > How to search character by character in mongodb array text field?

问题描述

I have documents in mongodb are like :

[{
  "_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. What I want to search here is if we have array of filter like {"tags" : ["member", "act"]} it will reply back id's 1 and 2 because here member is full match and act partial match in two documents.
  2. if I have filter like {"tags" : ["mem"] } then it should reply id's 1 and 3
  3. One more case If I have filter like {"tags" : ["member", "active"]} then it should answer only 1.

标签: mongodbmongodb-query

解决方案


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

  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);
    

推荐阅读