Himanshu Teotia
Himanshu Teotia

Reputation: 2185

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.

Upvotes: 1

Views: 429

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151092

You basically need two concepts here.

  1. Convert each input string of the array into an Regular expression anchored to the "start" of the string:

  2. Apply the list with the $all operator to ensure "all" matches:

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

Upvotes: 3

Related Questions