1

I am starting with MongoDb on c#. At the end, I need function which simply checks if the user exists in DB -thats it. I am a complete beginner so naturally example right from MongoDb tutorial does not work here are examples:

public  static async Task<List<User>> QueryDB(User u)
{
    var collection = _database.GetCollection<User>("UserData");
    var filter = Builders<User>.Filter.Eq("id", u.id);
    var result = await collection.Find(filter).ToListAsync();
    return result;

}

or

public  static async Task<long> QueryDB(User u)
{
    var collection = _database.GetCollection<User>("UserData");
    var filter = Builders<User>.Filter.Eq("id", u.id);
    var result = await collection.Find(filter).CountAsync();
    return result;

}

What is wrong with these functions? Or how should I call them? Because now it throws a timeout. Can this be done without async/await? I think I don't need it

cramopy
  • 3,459
  • 6
  • 28
  • 42
Anna F
  • 41
  • 6

1 Answers1

0

I would suggest using FindAsync, it works better and you prevent deadlocks in c# and let mongo do its job.

public async Task<List<User>> QueryDB(User u)
{
    var collection = _database.GetCollection<User>("UserData");
    var filter = Builders<User>.Filter.Eq(us => us.id, u.id); //best practice to prevent errors on field name such as extra letter or capital vs lowercase.
    List<User> fetchedUsers = new List<User>()
    using (var cursor = await collection.FindAsync(filter))
    {
          while (await cursor.MoveNextAsync())
          {
                 var batch = cursor.Current;
                  foreach (User user in batch)
                        fetchedUsers.Add(user);
          }
    }
    return fetchedUsers;

  }

if you want to "advance" you can use this method to all classes that have id field

public async Task<List<T>> QueryDB(this IMongoCollection<T> collection, T entity) where T : Idable
    {
        var filter = Builders<T>.Filter.Eq(ts => ts.id, entity.id);
        List<T> fetchedData = new List<T>()
        using (var cursor = await collection.FindAsync(filter))
        {
              while (await cursor.MoveNextAsync())
              {
                     var batch = cursor.Current;
                      foreach (T res in batch)
                            fetchedData.Add(res);
              }
        }
        return fetchedData;

      }

interface Idable
{
string id {get;};
}

public class User : Idable
{
...
}

you simply have this method "attached" to all your collections now. just create a list, lets say type of User, and call the collection.QueryDB(User u) and you will get a list of all users with the same id, yes..probably only 1, but you can modify this method and just play with it.

Ori Refael
  • 2,888
  • 3
  • 37
  • 68
  • Thanks! But when I call this function from another (also using await) code after the call just is not executed - and program finishes, same as with my functions before. Do you know whats happening? – Anna F Oct 04 '15 at 13:57
  • I couldn't understand you, sorry. can you explain abit more? – Ori Refael Oct 04 '15 at 13:57
  • Sorry - I hit Enter))) My comment was: Thanks! But when I call this function from another (also using await) code after the call just is not executed - and program finishes, same as with my functions before. Do you know whats happening? – Anna F Oct 04 '15 at 13:58
  • maybe you're using a Console Application? just hit Console.Read() at the end of your project. also, i would suggest you to just add a breakpoint before calling this method and check what happens. – Ori Refael Oct 04 '15 at 13:59
  • That is exactly what I'm doing, after a function call List users = await QueryDB(u); Console.WriteLine(users[0]); Console.ReadLine(); – Anna F Oct 04 '15 at 14:03
  • WriteLine and ReadLine are not executed – Anna F Oct 04 '15 at 14:04
  • and this code block is in the same class as the QueryDb is? can you wrap this in try catch, also QueryDb method and tell me if there is an exception? – Ori Refael Oct 04 '15 at 14:05
  • Yes, its in the same class, and it does not throw any exceptions(( I did use try-catch in both functions – Anna F Oct 04 '15 at 14:14
  • ok, try me first code suggestion, and debug it.. put a breakpoint on the first method row and tell me what happens..(breakpoint doesnt hit/cant skip to after 'await' row/etc..) – Ori Refael Oct 04 '15 at 14:19
  • Program finishes after this line: using (var cursor = await collection.FindAsync(filter)) . Can this be something with my connection to DB (db queries work fine from the console, but maybe I did not specify smth fron the code?) – Anna F Oct 04 '15 at 14:31
  • i would say that you have issues connecting to mongodb, its not code method issue.. try connecting the database via Robomongo or smth and check that you see some collections there, also see that your connection credentials are ok. – Ori Refael Oct 04 '15 at 14:35
  • I see my collections via Robomongo, also when I run my program this is what I see in cmd: – Anna F Oct 04 '15 at 14:52
  • 2015-10-04T17:49:16.798+0300 I NETWORK [initandlisten] waiting for connections on port 27017 2015-10-04T17:49:23.327+0300 I NETWORK [initandlisten] connection accepted from 127.0.0.1:54987 #1 (1 connection now open) 2015-10-04T17:49:29.939+0300 I NETWORK [initandlisten] connection accepted from 127.0.0.1:54988 #2 (2 connections now open) 2015-10-04T17:49:29.950+0300 I NETWORK [conn1] end connection 127.0.0.1:54987 ( 1 connection now open) 2015-10-04T17:49:29.950+0300 I NETWORK [conn2] end connection 127.0.0.1:54988 ( 1 connection now open) – Anna F Oct 04 '15 at 14:52
  • (2 connections now open) -this happens on the line which finishes the program. extra connection opened? – Anna F Oct 04 '15 at 14:53
  • is 2nd connection happening when I create another collection variable, anyway it should not affect it – Anna F Oct 04 '15 at 14:55
  • well, sorry.. i give up..it hard to figure it out when I cant be in-front of it. check if the port you're using is configured well or smth. just check in google.. the mongo installation is pretty messed up, just go over it again and double check its working well.. – Ori Refael Oct 04 '15 at 15:02