1

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.

1 Answer 1

3

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);
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.