0

我的用户集合将包含这样的数据

{ name:"steve" }, { name:"david" }, { name:"sana" }, { name:"robert" }

我的查询是这样的

 var myCollections= _database.GetCollection<RawBsonArray>("users");
 var query = Query.Matches("name", "Steve Sam Steward Savior Sana");
 myCollections.Find(query);

上面的查询将找到与"Steve Sam Steward Savior Sana"匹配的所有用户名。但我希望任何用户名与“Steve Sam Steward Savior Sana”中的任何单词匹配

如何使上述查询反向工作

预期结果是 { name:"steve" },{ name:"sana" }

我做了ForEach循环,但我不确定这是否是正确的方法。

这就是我想要实现的目标

_users.Any(x => "Steve Sam Steward Savior Sana".ToLower().Contains(x.name.ToLower()));
4

2 回答 2

0

I think what you need is the $in operator. Although, I'm not familiar with C#, this is how it can be done in the shell:

db.users.find({"name":{$in:["Steve", "Sam", "Steward", "Savior", "Sana"]}})

I hope this will help you come up with the equivalent in C#.

于 2014-03-27T00:31:34.180 回答
0

您可以使用:

var usernames = new List<string>() {@"Steve", @"Sam", @"Steward", @"Savior", @"Sana"};
// regex token list
var tokens = new List<string>();
for (var i = 0; i < usernames.Count; i++)
{
    // create the regex format
    var userRegex = string.Format("^{0}", usernames[i]);
    tokens.Add(userRegex);
}
var searchByUsernameRegex = string.Join(@"|", tokens);
Collection.Find(Query.Matches("Username", new BsonRegularExpression(searchByUsernameRegex))).ToList();

或者

// regex token list
var tokens = new List<string>();
for (var i = 0; i < users.Count; i++)
{
    // create the regex format
    var userRegex = string.Format("^{0}", users[i]);
    tokens.Add(userRegex);
}
// create regex to match the usernames
var regexes = tokens.Select(x => new Regex(x)).ToList();
// construct the query
var usersQuery = Query.In("Username", new BsonArray(regexes));
于 2014-03-27T22:41:26.553 回答