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

edx
edx
152 Points
41 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: 674
Total Answered: 1
Total Marked As Answer: 1
Posted On: 08-Jun-2020 02:35

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
1402 Points
236 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