Search code examples
c#mongodbmongodb-.net-driver

Inserting object to mongodb using c#


Iam trying to insert object to mongodb and I didnt find how. In my way the object inserted gets the id 00000

Here is my code:

public static async Task InsertData<T>(string collection_name, object insertData) 
DB mongoConnection = new DBconnection();

var collection = mongoConnection._database.GetCollection<object>(collection_name);

await collection.InsertOneAsync(insertData)
}

Solution

  • What is the sample model of insertData?

    MongoDB should generate id automatically if you mark Id field in your models with attributes:

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }