Donate

Return Last Inserted ID In MongoDB Using C# In ASP.NET MVC

Good evening developers!
The current project that I'm working with retrieves records from SQL Server and MongoDB. And it's my first time to use the NoSQL db in a real world project. I've attended training before but using the NoSQL db was not approved by the customer. Going back to the topic of this post, I was wondering if there's a similar approach in MongoDB to return the last inserted _id just like in C#'s code like this:
int id = Convert.ToInt32(cmd.ExecuteScalar());
After experimenting and debugging, I can get the newly inserted record's id right after the insert statement by retrieving the id from the newly inserted BSONDocument itself.
public void Add(UserActivity userActivity)
{
 var activityDocument = new BsonDocument
 {
  {"ActivityUserName", userActivity.ActivityUserName },
  {"ActivityName", userActivity.ActivityName },
  {"ActivityModule", userActivity.ActivityModule },
  {"ActivityDate", userActivity.ActivityDate },
  {"ActivityApplicationType", userActivity.ActivityApplicationType },
 };
 
 mongoCollectionBSON = mongoDB.GetCollection<BsonDocument>("UserActivity");
 mongoCollectionBSON.InsertOne(activityDocument);
 
 //do something with the id
 var id = activityDocument["_id"];
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations