How to create indexes in MongoDB via .NET

Starting from v2.0 of the driver there’s a new async-only API. The old API should no longer be used as it’s a blocking facade over the new API and is deprecated. The currently recommended way to create an index is by calling and awaiting CreateOneAsync with an IndexKeysDefinition you get by using Builders.IndexKeys: static async … Read more

MongoDB GridFs with C#, how to store files such as images?

Following example show how to save file and read back from gridfs(using official mongodb driver): var server = MongoServer.Create(“mongodb://localhost:27020”); var database = server.GetDatabase(“tesdb”); var fileName = “D:\\Untitled.png”; var newFileName = “D:\\new_Untitled.png”; using (var fs = new FileStream(fileName, FileMode.Open)) { var gridFsInfo = database.GridFS.Upload(fs, fileName); var fileId = gridFsInfo.Id; ObjectId oid= new ObjectId(fileId); var file = … Read more

.NET best practices for MongoDB connections?

Most answers here are outdated and are no longer applicable as the .net driver has matured and had numberless features added. Looking at the documentation of the new 2.0 driver found here: http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/connecting/ The .net driver is now thread safe and handles connection pooling. According to documentation It is recommended to store a MongoClient instance … Read more

MongoDB C# Driver – Ignore fields on binding

Yes. Just decorate your UserModel class with the BsonIgnoreExtraElements attribute: [BsonIgnoreExtraElements] public class UserModel { public ObjectId id { get; set; } public string Email { get; set; } } As the name suggests, the driver would ignore any extra fields instead of throwing an exception. More information here – Ignoring Extra Elements.

How to get the Mongo database specified in connection string in C#

Update: MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code: var _server = new MongoClient(connectionString).GetServer(); It’s easy. You should first take database name from connection string and then get database by name. Complete example: var connectionString = “mongodb://localhost:27020/mydb”; //take database name from connection string var _databaseName = MongoUrl.Create(connectionString).DatabaseName; var _server = MongoServer.Create(connectionString); … Read more

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