1

I have been trying to insert values in a table in mongoDB using MVC but I got stuck very early getting an error and could not resolve it. The controller code is

[HttpPost]
public ActionResult Registration(UserModel um)
{
    //Connect to MongoDB
    MongoClient client = new MongoClient("mongodb://localhost:27017");

    var objDatabse = client.GetDatabase("MVCTestDB");

    MongoCollection<BsonDocument> UserDetails = objDatabse.GetCollection<BsonDocument>("Users");

    //Insert into Users table.
    UserDetails.Insert<UserModel>(um);
    return View();
}

I am getting an error at the line : MongoCollection UserDetails = objDatabse.GetCollection("Users");

The error is : "cannot implicitly convert type 'MongoDB.Driver.IMongoDatabase' to 'MongoDB.Driver.MongoDatabase'.An explicit conversion exists(are you missing a cast?)" What I understand is there might be a type casting error.

0

1 Answer 1

2

WHy not going for:

   IMongoCollection<UserModel> UserDetails = objDatabse.GetCollection<UserModel>("Users");

UserDetails.InsertOne(um);

Here is working example from my code that is just tested (are you using the latest driver version):

var connectionString = "mongodb://localhost:27017";

var mongoClient = new MongoClient(connectionString);

IMongoDatabase db = mongoClient.GetDatabase("Trading");

IMongoCollection<Account> = Database.GetCollection<Account>("Account");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man. It worked :) :) I had no idea about IMongoCollection. I am new to this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.