问题
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"]
}]
- What I want to search here is if we have array of filter like
{"tags" : ["member", "act"]}
it will reply back id's1
and2
because heremember
is full match andact
partial match in two documents. - if I have filter like
{"tags" : ["mem"] }
then it should reply id's1
and3
- One more case If I have filter like
{"tags" : ["member", "active"]}
then it should answer only1
.
回答1:
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);
来源:https://stackoverflow.com/questions/53148402/how-to-search-character-by-character-in-mongodb-array-text-field