How is an IAsyncCursor used for iteration with the mongodb c# driver?

You have 3 options: Use the built-in driver method (e.g. ForEachAsync, ToListAsync). On C# 8.0 and above you can convert the IAsyncCursor into an IAsyncEnumerable and use await foreach or any async LINQ operator. Iterate over the IAsyncCursor. Built-in Driver Methods The driver has some LINQ-like extension methods for IAsyncCursor, like AnyAsync, ToListAsync, etc. For … Read more

MongoDB InsertMany vs BulkWrite

Ok that’s two questions: InsertMany vs BulkWrite Using BulkWrite you can do many operations in a single connection to mongoDB. Internally, InsertMany uses BulkWrite, so there’s no difference, it’s just for convenience. This question was already solved. Sync vs Async When you perform a sync operation, your aplication will wait for MongoDB to finalize the … Read more

How do I use the AsQueryable method asynchronously with MongoDb C# Driver 2.1?

You’re returning the wrong type from the GetFiltered function. It should be returning an IMongoQueryable<MyType> instead of IQueryable<MyType>: public IMongoQueryable<MyType> GetFiltered(Expression<Func<MyType, bool>> predicate) { return Database.GetCollection<MyType>(typeof(MyType).Name).AsQueryable() .Where(predicate); } You can then successfully call it as: var myTypes = await MyRepository.GetFiltered(t => t.Id == 1).ToListAsync();

BsonSerializationException when serializing a Dictionary to BSON

The problem is that the new driver serializes dictionaries as a document by default. The MongoDB C# driver has 3 ways to serialize a dictionary: Document, ArrayOfArrays & ArrayOfDocuments (more on that in the docs). When it serializes as a document the dictionary keys are the names of the BSON element which has some limitations … Read more

Mongodb — include or exclude certain elements with c# driver

Update: With new driver version (1.6+) you can avoid fields names hard-coding by using linq instead: var users = usersCollection.FindAllAs<T>() .SetFields(Fields<T>.Include(e => e.Id, e => e.Name)); You can do it via SetFields method of mongodb cursor: var users = usersCollection.FindAllAs<T>() .SetFields(“_id”) // include only _id .ToList(); By default SetFields includes specified fields. If you need … Read more

Convert MongoDB BsonDocument to valid JSON in C#

MongoDB.Bson (2.5+) has support to map between BsonValues and .Net objects. BsonTypeMapper Class To map a BsonValue (or BsonDocument) to .Net object use var dotNetObj = BsonTypeMapper.MapToDotNetValue(bsonDoc); You can then use your choice of serialization library. For example, JsonConvert.SerializeObject(dotNetObj); If you have a List of BsonDocument var dotNetObjList = bsonDocList.ConvertAll(BsonTypeMapper.MapToDotNetValue);

Creating MongoDB Unique Key with C#

The unique index only needs to be created once, after that any document inserts that contain a duplicate email address will fail. Here’s an example: var server = MongoServer.Create(“mongodb://localhost”); var db = server.GetDatabase(“myapp”); var users = db.GetCollection<User>(“users”); users.EnsureIndex(new IndexKeysBuilder() .Ascending(“EmailAddress”), IndexOptions.SetUnique(true)); var user1 = new User { EmailAddress = “joe@example.com” }; var user2 = new … Read more

Query MongoDB Using ‘ObjectId’

You need to create an instance of ObjectId and then query using that instance, otherwise your query compares ObjectIds to string and fails to find matching documents. This should work: var query_id = Query.EQ(“_id”, ObjectId.Parse(“50ed4e7d5baffd13a44d0153”)); var entity = dbCollection.FindOne(query_id); return entity.ToString();

How to check if collection exists in MongoDB using C# driver?

@im1dermike answer is no longer working for c# driver version 2.0+ Here is an alternative: public async Task<bool> CollectionExistsAsync(string collectionName) { var filter = new BsonDocument(“name”, collectionName); //filter by collection name var collections = await GetDatabase().ListCollectionsAsync(new ListCollectionsOptions { Filter = filter }); //check for existence return await collections.AnyAsync(); }

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)