简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM