MongoDB substring product search order by highest match

℡╲_俬逩灬. 提交于 2019-12-04 19:03:55

First of all, you can combine multiple filters with using & operator like this:

var builder = Builders<Product>.Filter;
FilterDefinition<Product> filter = builder.Empty;
filter &= builder.Eq("Color", "blue");
filter &= builder.Eq("Retailer", "adidas");
filter &= builder.Eq("Category", "men");

Then, you can use Regex to filter the products the names of which contain any rest words/all rest words.
OR search (the name contains "cotton" OR "spiderman")

var restWords = new string[] { "cotton", "spiderman" };
var orReg = new System.Text.RegularExpressions.Regex(string.Join("|", restWords));
filter &= builder.Regex("Name", BsonRegularExpression.Create(orReg));

List<Product> filteredList = products.Find(filter).ToListAsync().Result;

AND search (the name contains "cotton" AND "spiderman")

foreach (var word in restWords)
{
    filter &= builder.Regex("Name", BsonRegularExpression.Create(new System.Text.RegularExpressions.Regex(word)));
}

List<Product> filteredList = products.Find(filter).ToListAsync().Result;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!