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.

jopasserat
  • 5,721
  • 4
  • 31
  • 50
nesimtunc
  • 849
  • 7
  • 28
  • Please note that now that official C# driver has LINQ support you should probably switch from using FluentMongo which is no longer supported. See http://stackoverflow.com/questions/9991722/transition-from-fluent-mongo-to-mongo-c-sharp-1-4-driver for more info. – Asya Kamsky Jun 03 '12 at 23:50

1 Answers1

1

It looks like you are using FluentMongo - the error you got is coming from there.

The likely candidate to cause this error is this line:

   orderby Guid.NewGuid()

This does not appear to be supported with FluentMongo. It means you probably want to use a different method of randomizing the returned record. FluentMongo does support OrderBy but their documentation only mentions ability to sort by field.

Note that something that maps from LINQ to SQL will not necessarily map to MongoDB query. Some related discussion about this is in this question and many others.

By the way, there is a lot of discussion about how to get a random document/object back from MongoDB, both on SO and on mongo-users list. There is even a write-up of it in Mongo Cookbook. I would recommend reviewing those for possible solution to your use case.

Community
  • 1
  • 1
Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
  • I developed a custom solution. Added all Id to cacheable List and get random one to send a query to db. – nesimtunc Oct 24 '12 at 16:54