如何在mongodb数组文本字段中逐字符搜索? [英] How to search character by character in mongodb array text field?

查看:58
本文介绍了如何在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"]
}]

  1. 我想在这里搜索的是,如果我们有像{"tags" : ["member", "act"]}这样的过滤器数组,它会回复id的12,因为这里member是两个文件中的完全匹配项,而act部分匹配.
  2. 如果我有类似{"tags" : ["mem"] }的过滤器,则它应该回复ID的13
  3. 还有一种情况,如果我有类似{"tags" : ["member", "active"]}的过滤器,那么它应该只回答1.
  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.

推荐答案

在这里,您基本上需要两个概念.

You basically need two concepts here.

  1. 将数组的每个输入字符串转换为固定在字符串开始"位置的正则表达式:

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆