【问题标题】:Searching for string pattern that matches string in array in MongoDB C#在MongoDB C#中搜索与数组中的字符串匹配的字符串模式
【发布时间】:2014-02-06 04:45:01
【问题描述】:

我似乎无法使用 C# 驱动程序在 MongoDB 中使用它。我现在已经花了一段时间没有任何运气。我有一个字符串数组,我想返回包含数组中任何单词的所有 mongo 文档。

我从集合中获取数组字符串。并且该数组将包含以下项目:["moon", "cow", "Neil"]

我有一个这样的集合:

{_id: "xxxxx1", story:"The cow jump over the moon"}
{_id: "xxxxx2", story:"Neil Armstrong landed on the moon in the 1960s"}
{_id: "xxxxx3", story:"The moon is very bright tonight."}
{_id: "xxxxx4", story:"Itsy winchie spider climb up the spout. moon is cool."}
{_id: "xxxxx5", story:"moon"}
{_id: "xxxxx6", story:"no text match here mate"}

因此,从数组和集合中,应该释放前 5 个文档,因为它们包含“moon”、“cow”或“Neil”。不应返回最后一个文档,因为它不包含任何这些单词。

下面是我卡住的代码。它只返回文档 xxxx5,因为它包含月亮而没有其他内容。我快到了,但不完全。希望有人能帮忙。

var userId = "12345";
var connectionString = ConfigurationManager.AppSettings["MongoDBConnectionString"];
var server = MongoServer.Create(connectionString);
var database = server.GetDatabase(ConfigurationManager.AppSettings["MongoDBDatabase"]);

var fCollection = database.GetCollection<BsonDocument>("words");
var fQuery = Query.EQ("UserId", userId);
var fDoc = fCollection.FindAs<Words>(fQuery).SetFields(Fields.Exclude("_id"));
var list = fDoc.ToList();

var words = list.Select(t => t.Word).ToArray();

var collection = database.GetCollection<BsonDocument>("stories");
var query = Query.In("story", new BsonArray(words);


var doc =     collection.Find(query).SetSortOrder(SortBy.Descending("Submitted")).Skip(skip).Take(limit);

var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
return doc.ToJson(jsonWriterSettings);

【问题讨论】:

    标签: c# .net arrays mongodb mongodb-.net-driver


    【解决方案1】:

    在 MongoDB 中搜索字符串时可以使用Regex

    Query.Matches("story","<Regex for: moon or cow or Neil>");
    

    查看here,了解如何编写匹配多个单词的正则表达式。基本上是这样的:

    ^(?=.*\bmoon\b)(?=.*\bcow\b)(?=.*\bNeil\b)
    

    总结:

    collection.Find(Query.Matches(
        "story",
        "^(?=.*\bmoon\b)(?=.*\bcow\b)(?=.*\bNeil\b)"))
        .SetSortOrder(SortBy.Descending("Submitted")).Skip(skip).Take(limit);
    

    【讨论】:

    【解决方案2】:

    您是否尝试过使用文本索引?这是 v2.4 中提供的一个测试版功能,您可以手动启用:http://docs.mongodb.org/manual/tutorial/enable-text-search/

    有关索引本身的信息,请参阅以下内容: http://docs.mongodb.org/manual/core/index-text/

    以下页面为文本搜索示例。 http://docs.mongodb.org/manual/reference/command/text/#dbcmd.text

    【讨论】:

    • 在 mongo shell 中,您可以执行 db.words.find( { story: /cow|land|moon/ } ),但不确定如何在 C# 中构造正则表达式——也许是 BsonRegularExpression。 Create(new Regex("cow|land|moon"))?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多