I'm writing a generic method to act like data access layer to insert document to MongoDB using C# .Net. My method looks like below. Collection here is a MongoCollection retrieved from MongoDB.
public async T Create(T entity){
await Collection.InsertOneAsync(entity);
}
I want to return the entity inserted or it's ID which is auto generated by MongoDB back. InsertOneAsync method is returning a task. I tried changing it as below. But its's return type is void.
Collection.InsertOneAsync(entity).GetAwaiter().GetResult();
Is there a way to get the id or entity back using InsertOneAsync method. I'm using MongoDB driver for C#.
Ids in MongoDB are generated on the client side.
If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.
In you case you can generate ObjectIds manually and return them from your method (using ObjectId.GenerateNewId()
) or return entire object since MongoDB driver will set proper _id value if you use [BsonId]
attribute
public async Task<T> Create(T entity) where T:class
{
await Collection.InsertOneAsync(entity);
return entity;
}
And pass a type parameter like:
public class MyClass
{
[BsonId]
public ObjectId Id { get; set; }
//other properties
}