3

When I use FindOne it said "'MongoClientExtensions.GetServer(MongoClient)' is obsolete: 'Use the new API instead.' Observer.Client" as a warning.

here is my code

collection.EnsureIndex(IndexKeys.Ascending("Username", "Type"), IndexOptions.SetUnique(true));
        var userlog = collection.FindOne(Query<UserLog>.Where(ul => ul.Username == username && ul.Type == type));
mostafakvd
  • 86
  • 1
  • 2
  • 10

2 Answers2

3

I wish this can help you just for your FindOne function

public async static Task<TModel> FindOne<TModel>(this IMongoCollection<TModel> collection, FilterDefinition<TModel> filter)
    {
        FindOptions<TModel> options = new FindOptions<TModel> { Limit = 1 };
        IAsyncCursor<TModel> task = await collection.FindAsync(filter, options);
        List<TModel> list = await task.ToListAsync();
        TModel result = list.FirstOrDefault();
        return result;
    }

or

public static T FindOne<T>(this IMongoCollection<T> collection, IMongoQuery query)
    {
        return collection.Find(query.ToBsonDocument()).FirstOrDefault();
    }

you can use these links for your EnsureIndex function

How to create indexes in MongoDB via .NET

Building indexes in MongoDB with .NET driver 2.0

Community
  • 1
  • 1
Yasser Bazrforoosh
  • 1,246
  • 10
  • 13
1

I haven't any idea about FindOne problem, because i'm not good at C#. But for the EnsureIndex: It isn't a good way to use.

  1. EnsureIndex Check indexes and this kind of using, leads to heavy and unnecessary round trips.
  2. Suppose the collection have multi-million of documents, and suddenly a unexpected event cause to remove the index. So EnsureIndex start to create index as foreground and freeze collection (without any management).
  3. I recommend you to use CreateIndex as the background and managed process for this kind of maintenance jobs.

Finally may this issue helps you

irmorteza
  • 1,576
  • 3
  • 19
  • 32