Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ernestoguimaraes/31f95ad17e90f8ee2fe5138647792f08 to your computer and use it in GitHub Desktop.
Save ernestoguimaraes/31f95ad17e90f8ee2fe5138647792f08 to your computer and use it in GitHub Desktop.
CODE SNIPPET TO ADD A NEW DOCUMENTO INTO A MONGODB COLLECTION USING C# MONGODB DRIVER
//Get The Connection String in your AppSettings.json
//Connect on MongoDB
var conn = _settings.GetSection("NOSQL:MongoConn").Value;
var mongoclient = new MongoClient(conn);
//Get your DataBase
var db = _settings.GetSection("NOSQL:CobrancaNOSQLDB").Value;
_mongoDB = mongoclient.GetDatabase(db);
//Get your Collection
var noSQLCollection = _settings.GetSection("NOSQL:TableNameCollection").Value;
var collection = _mongoDB.GetCollection<BsonDocument>(noSQLCollection);
//Very important - entity is your object represent you a Class in your Model.
var document = new BsonDocument(entity.ToBsonDocument());
await collection.InsertOneAsync(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment