1

I used to use this command FindOne to query the result from mongoDB with C# in the past and it can be used at that time. But now I use the same code but it doesn't work. What should I use instead of FindOne?

My code is like this:

        var connectionString = "mongodb://localhost";
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("extend");
        var collection = database.GetCollection<Entity>("user");

        var query = Query<Entity>.EQ(e => e.user_id, int.Parse(targetUser.CurrentUser));
        var entity_TargetUser = collection.FindOne(query);

When I try to run it, I got this error

Error CS1061: 'IMongoCollection<Entity>' does not contain a definition for 'FindOne' and no extension method 'FindOne' accepting a first argument of type 'IMongoCollection<Entity>' could be found (are you missing a using directive or an assembly reference?) (CS1061)

What command that I can use instead of FindOne?

Phannakan
  • 81
  • 1
  • 9
  • If i got you right... There is no FindOne method. You should use .Find(...).SingleOrDefault() or .Find(...).FirstOrDefault() depend on your needs. There are plenty of methods there. – Artyom Apr 12 '18 at 08:46
  • Thank you @Artyom I try your suggestion but there's a problem with the return type. It isn't the same as I want. I'm trying to figure it out. – Phannakan Apr 12 '18 at 12:00
  • Take a look here: https://stackoverflow.com/questions/31171451/getting-a-single-object-from-mongodb-in-c-sharp – Artyom Apr 12 '18 at 12:24

2 Answers2

1

You are dealing with an id, so I assume each one is unique - if they aren't, they should be. Assuming user_id is unique then I would do the following

public static class MongoDataService
{
    public static async Task<List<BsonDocument>> GetDocumentCollectionAsync(
        MongoClient client, FilterDefinition<BsonDocument> filter,
        string databaseName, string collectionName, CancellationToken token,
        int? limit = null)
    {
        return await Task.Run(async () =>
        {
            long i = 1;
            List<BsonDocument> items = new List<BsonDocument>();
            var collection = GetCollection<BsonDocument>(client, databaseName, collectionName);
            using (var cursor = await collection.FindAsync(filter))
            {
                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    foreach (var doc in batch)
                    {
                        items.Add(doc);

                        if (token.IsCancellationRequested || i == limit)
                            return items;
                        i++;
                    }
                }
            }
            return items;
        }, token);
    }
}

This method with the correct filter will return single documents, or can be used to return batches of documents again according to the imposed filter. Calling this method for your case, you can do

var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Eq("user_id", int.Parse(targetUser.CurrentUser));
var documents = await MongoDataService.GetDocumentCollectionAsync(client, filter, "extend", "user", token, null);

There are other methods to do what you want, but this should do what you want.

Note, I am assuming you are using the offical MongoDB.Driver.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277
  • Thank you @MoonKnight I use your code and there're still errors `Error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. (CS4033)` , `Error CS0103: The name 'GetCollection' does not exist in the current context (CS0103)` and `Error CS1579: foreach statement cannot operate on variables of type '?' because '?' does not contain a public definition for 'GetEnumerator' (CS1579)` How to correct this? – Phannakan Apr 12 '18 at 11:09
0

you can do something like this:

    var connectionString = "mongodb://localhost";
    var client = new MongoClient(connectionString);
    var database = client.GetDatabase("extend");
    var collection = database.GetCollection<Entity>("user");

    var query = Query<Entity>.EQ(e.user_id,int.Parse(targetUser.CurrentUser));

    var entity_TargetUser = collection.AsQueryable().where(query).single();

or

    var connectionString = "mongodb://localhost";
    var client = new MongoClient(connectionString);
    var database = client.GetDatabase("extend");
    var collection = database.GetCollection<Entity>("user");



    var entity_TargetUser = collection.AsQueryable().where(e=>e.user_id == 
    int.Parse(targetUser.CurrentUser)).single();
v379
  • 23
  • 4