我正在寻找字符串"JESÚS"
,但仅返回具有指定字符串的文档,我需要进行搜索以忽略重音和大写字母。
我正在使用C#和mongodb驱动程序。
我的mongodb中保存了两个文档:
_id:5d265f3129ea36365c7ca587
TRABAJADOR:"JESUS HERNANDEZ DIAZ"
_id:5d265f01db86a83148404711
TRABAJADOR:"JESÚS HERNÁNDEZ DÍAZ"
在具有mongo驱动程序的Visual C#中:
var filter = Builders<BsonDocument>.Filter.Regex("TRABAJADOR", new BsonRegularExpression(string.Format(".*{0}.*", "JESÚS"), "i"));
var result = collection.Find(filter, new FindOptions() { Collation = new Collation("es", strength: CollationStrength.Primary, caseLevel:true) }).ToList();
output = JsonConvert.SerializeObject(result);
return output;
如果我搜索"JESÚS"
,则实际输出为:
_id:5d265f01db86a83148404711
TRABAJADOR:"JESÚS HERNÁNDEZ DÍAZ"
但是实际上我期望得到以下输出:
_id:5d265f3129ea36365c7ca587
TRABAJADOR:"JESUS HERNANDEZ DIAZ"
_id:5d265f01db86a83148404711
TRABAJADOR:"JESÚS HERNÁNDEZ DÍAZ"
答案 0 :(得分:0)
您需要查看两个字段才能同时获得这两个字段:
var filter = Builders<BsonDocument>.Filter;
var query = filter.Regex("TRABAJADOR", new BsonRegularExpression(string.Format(".*{0}.*", "JESÚS"), "i")) & filter.Regex("WORKER", new BsonRegularExpression(string.Format(".*{0}.*", "JESÚS"), "i"));
将这两行替换为第一行,并为您的查找提供 query 。
我没有测试它,希望它对您有用!
答案 1 :(得分:0)
我建议您创建一个文本索引,并将其默认语言设置为“ none”,以使其对变音符号不敏感,然后按如下所示进行$ text搜索:
db.Project.createIndex(
{
"WORKER": "text",
"TRABAJADOR": "text"
},
{
"background": false,
"default_language": "none"
}
)
db.Project.find({
"$text": {
"$search": "jesus",
"$caseSensitive": false
}
})
这是生成上述查询的C#代码。我正在使用我的图书馆MongoDB.Entities简洁起见。
using MongoDB.Entities;
using System;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class Project : Entity
{
public string WORKER { get; set; }
public string TRABAJADOR { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
DB.Index<Project>()
.Key(p => p.WORKER, KeyType.Text)
.Key(p => p.TRABAJADOR, KeyType.Text)
.Option(o => o.DefaultLanguage = "none")
.Option(o => o.Background = false)
.Create();
(new[] {
new Project { WORKER = "JESUS HERNANDEZ DIAZ"},
new Project { TRABAJADOR = "JESÚS HERNÁNDEZ DÍAZ"}
}).Save();
var result = DB.SearchText<Project>("jesus");
Console.WriteLine($"found: {result.Count()}");
Console.Read();
}
}
}