deniz07
deniz07

Reputation: 43

Inserting multiple data into MongoDB using c#

I just started to use MongoDB and I wanted to ask how to put multiple data into one variable. What i want to do is User registration with windows forms. But whenever i check on internet i see people creating multiple variables for each data. For example while we can:

INSERT INTO users (username, password) VALUES ('{user}', '{pass}');

execute this code on mysql but on mongoDB we need to create variables for every user that registered. So that means its not automatic.

Upvotes: 1

Views: 4237

Answers (1)

Fermin
Fermin

Reputation: 36101

You've not mentioned which driver you are using so I assume you're using the official .net driver.

To insert multiple documents into MongoDB you would use the InsertManyAsync method. An example is shown in the official MongoDB c# driver documentation.

An example method is:

public Task InsertUsers(IEnumerable<User> users)
{
  // create client
  const string connectionString = "mongodb://localhost:27017";      
  var client = new MongoClient(connectionString);

  // get database
  var database = client.GetDatabase("myDb");

  // get user collection
  var collection = _database.GetCollection<User>("users");

  // insert users and return async Task
  return collection.InsertManyAsync(users);
}

But whenever i check on internet i see people creating multiple variables for each data.

I would recommend reading up on the difference between a relational database (like MySQL) and a document DB (like MongoDB) as, while they do both store data, they are quite different technologies and are for different problems.

Upvotes: 4

Related Questions