Reputation: 2185
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"]
}]
{"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.{"tags" : ["mem"] }
then it should reply id's 1
and 3
{"tags" : ["member", "active"]}
then it should answer only 1
.Upvotes: 1
Views: 429
Reputation: 151092
You basically need two concepts here.
Convert each input string of the array into an Regular expression anchored to the "start" of the string:
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