如何在mongodb数组文本字段中逐字符搜索? [英] How to search character by character in mongodb array text field?
本文介绍了如何在mongodb数组文本字段中逐字符搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在mongodb中的文档如下:
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"]}
这样的过滤器数组,它会回复id的1
和2
,因为这里member
是两个文件中的完全匹配项,而act
部分匹配. - 如果我有类似
{"tags" : ["mem"] }
的过滤器,则它应该回复ID的1
和3
- 还有一种情况,如果我有类似
{"tags" : ["member", "active"]}
的过滤器,那么它应该只回答1
.
- 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
.
推荐答案
在这里,您基本上需要两个概念.
You basically need two concepts here.
-
将数组的每个输入字符串转换为固定在字符串开始"位置的正则表达式:
Convert each input string of the array into an Regular expression anchored to the "start" of the string:
在列表中使用 $all
运算符,以确保所有"匹配:
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);
这篇关于如何在mongodb数组文本字段中逐字符搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文