Khorshid February 2016

is filter is replaceable of query in mongo queries using c#?

I'm new to mongo in c#

I found tow ways to find documents based on search critiria:

the first using filter:

var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075");
var result = await collection.Find(filter).ToListAsync();

The second using query:

MongoCollection<BsonDocument> books;
var query = Query.EQ("author", "Kurt Vonnegut");
foreach (BsonDocument book in books.Find(query)) {
    // do something with book
}

What's the best way to find documents based to what MongoDB recommendation?

Answers


IsaacBok February 2016

The first way you mentioned is quite fine. You might want to incorporate using a mongo cursor as well to allow you to iterate through results

    var collection = _database.GetCollection<BsonDocument>("restaurants");
    var filter = Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075");
    using(var _cursor = await collection.Find(filter).ToCursorAsync())
    {
        while(await _cursor.MoveNextAsync())
        {
            foreach(var _document in _cursor.Current) //gets current document
            {
                //you can do things like get the _id of the document
                var _id = _document["_id"];
            }
        }
    }


octavioccl February 2016

As far I know query builders (like your second example using Query.EQ) belong to old versions of C# drivers (1.X) (see Query class). Also I suggest you to see Builder section in this link that confirm query builders is the old way to consult data.

After the release of the 2.0 version of the .NET driver, a lot of changes were made, including the way of consult the data (you can read more about that in this link). If you are using the last C# driver version you should use your first approach.

Post Status

Asked in February 2016
Viewed 1,912 times
Voted 5
Answered 2 times

Search




Leave an answer