mongodb - 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"]
}]
- 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
.
解决方案
你在这里基本上需要两个概念。
将数组的每个输入字符串转换为锚定到字符串“开始”的正则表达式:
使用运算符应用列表
$all
以确保“全部”匹配: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);
推荐阅读
- amazon-web-services - AWS - 如何将 S3 工件从 codebuild 发送到 EC2 实例
- django - 将 URL 设置为使用 slug 而不是 ID
- python - 为什么 opencv dnn blobfromimages 的工作速度比通过 blobfromimage 逐个发送的单个图像进行批处理要慢?
- spring-boot - 更新嵌套项目 aws-dynamo-db(AWS SDK for Java 2.0)
- windows - 如何使用 PowerShell 设置 DNS 后缀和注册?
- python - 如何使 tableview 代表消失在边距/标题后面?
- django - Django:检查记录是否存在于两种不同的状态
- python - 使用 reduce() 获得最大价值
- windows - 如何在 Jupyter Notebook 中测量 CPU 时间
- python - python中有没有办法同时扩展数据框的行和列?