Home > Back-end >  Write Json document to mongoDB using C#
Write Json document to mongoDB using C#

Time:07-20

I have a CSV file which contains

Name, EmployeID
Kishore, 235

I need to read Name & EmployeID from above csv file, update name and EmployeID in below JSON and write updated Json to mongodb collection.

{    
    "name": kishore,
    "EmployeID": "235",
    "Gender": "Male",
}

Can you please help me with any code snippet using C#

Appreciate your help

CodePudding user response:

The simplest form to mimic the insert statement from your comment is to use a collection of type BsonDocument and insert the document like this:

var client = new MongoClient("MONGODB_CONNSTR");
var db = client.GetDatabase("MONGODB_DB_NAME");
var employees = db.GetCollection<BsonDocument>("employees");
await employees.InsertOneAsync(new BsonDocument
            {
                { "EmployeeId", 235 },
                { "Name", "kishore" },
                { "Gender", "Male" }
            });

This creates the following document:

{  
  "_id": {    
    "$oid": "62d7b6d25c248b9684eee64d"  
  },  
  "EmployeeId": 235,
  "Name": "kishore",
  "Gender": "Male"
}
  • Related