How to get collection back after insert/update in mongodb?

edx
edx
506 Points
24 Posts

I'm using mongodb.driver in .net core project. In this using following method to insert and update collections:

mongoDB.GetCollection("COLLECTION_NAME").InsertOneAsync(doc);
mongoDB.GetCollection("COLLECTION_NAME").ReplaceOne(filter, doc);

How to get collection back after insert/update in mongodb?

Views: 1290
Total Answered: 1
Total Marked As Answer: 1
Posted On: 08-Jun-2020 02:35

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

Try some thing:

For insert=>

public async Task<TEntity> AddAsync(TEntity entity)
{
    var doc = SetId(entity);
    await mongoDB.GetCollection<BsonDocument>(COLLECTION_NAME).InsertOneAsync(doc);
    return entity;
}

private BsonDocument SetId(TEntity entity)
{
    var bsonDoc = entity.ToBsonDocument();
    bsonDoc["_id"] = mongoDB.GetUniqueMongoDatabaseIDForRecord();
    return bsonDoc;
}

 

For update=>

public async Task<TEntity> UpdateAsync(TEntity entity)
{
    var id = GetId(entity);
    FilterDefinition<TEntity> filter = Builders<TEntity>.Filter.Eq("_id", id);
    await mongoDB.GetCollection<TEntity>(COLLECTION_NAME).ReplaceOneAsync(filter, entity);
    return entity;
}

private BsonValue GetId(TEntity entity)
{
    var bsonDoc = entity.ToBsonDocument();
    return bsonDoc.GetElement("_id").Value;
}
Posted On: 19-Jan-2022 23:48
Thanks
 - edx  01-Feb-2022 02:07
 Log In to Chat