I have a database that created in MongoDB using Robomongo tool. How can I update these data in Web API by its default POST, PUT, DELETE methods in ValuesControllers.cs?
Database name : StudentInfo Collection Name : Student
_id : ObjectId(),
name : "lqbal",
department : "CSE",
phone : "0194949402"
Best How To :
Here is an example of the
POST Action. WebApi can perform Model binding so it can take content from the body of the
POST action and bind it to a c# entity - in this case the
Student object. Here is the content of the
Also make sure to set the
Content-Type of the
application/json so WebApi can perform the correct model binding.
The code in the
POST action then has to look up the student in question in the DB. Once it retrieves the
Student object, it can update the values and then save the object back to the DB.
public void Post([FromBody]Student value)
var student = ((MongoCollection)collection).AsQueryable<Student>().First(c => c.name == value.name);
student.department = value.department;
student.phone = value.phone;
The concept for the
PUT action is similar to this
POST action except that a new
Student object is created.
DELETE action is straightforward as well is similar to the
GET action - you only need to pass the
ID of the record to delete in the query string and then just delete it in the action controller.
Here is a link to how to remove a document with the mongo c# driver
Mongo c# Driver - Remove an Existing Document