0

I want to take a record randomly from MongoDB using Linq in C#. Here is what I'm doing.

public string RandomWord()
{
    using (Mongo mongo = new Mongo(_mongoConfig.BuildConfiguration()))
    {
        try
        {
            mongo.Connect();
            var db = mongo.GetDatabase(_dbName);
            IMongoCollection<dic_words> collection = db.GetCollection<dic_words>();
            return 
                (from w in collection.Linq()
                where w.word.Length > 2
                orderby Guid.NewGuid()
                select w).Take(1).FirstOrDefault().word;
        }
        catch (Exception)
        {
            throw;
        }
    }
}

And here is the error I got

The query is too complex to be processed by MongoDB. Try building a map-reduce query by hand or simplifying the query and using Linq-to-Objects.

Thanks in advance.

4

1 回答 1

1

看起来你正在使用 FluentMongo - 你得到的错误来自那里。

导致此错误的可能候选者是这一行:

   orderby Guid.NewGuid()

FluentMongo 似乎不支持此功能。这意味着您可能希望使用不同的方法来随机化返回的记录。FluentMongo 确实支持 OrderBy 但他们的文档只提到了按字段排序的能力。

请注意,从 LINQ 映射到 SQL 的内容不一定会映射到 MongoDB 查询。关于这个问题的一些相关讨论在这个问题和许多其他问题中。

顺便说一句,在 SO 和 mongo-users 列表上都有很多关于如何从 MongoDB 获取随机文档/对象的讨论。Mongo Cookbook中甚至有一篇关于它的文章。我建议您查看那些可能的解决方案来解决您的用例。

于 2012-06-03T22:59:08.740 回答