How to insert data into a mongodb collection using the c# 2.0 driver?
54,624
Solution 1
This is the method I created for inserting data into MongoDB, which is working fine now.
static async void DoSomethingAsync()
{
const string connectionString = "mongodb://localhost:27017";
// Create a MongoClient object by using the connection string
var client = new MongoClient(connectionString);
//Use the MongoClient to access the server
var database = client.GetDatabase("test");
//get mongodb collection
var collection = database.GetCollection<Entity>("entities");
await collection.InsertOneAsync(new Entity { Name = "Jack" });
}
Solution 2
The reason is you need to wait to get the store to create the document. In this case collection.InsertOneAsync(entity); the execution exit before creating the document.
Either Console.ReadKey() or collection.InsertOneAsync(entiry).Wait() or any other form of stopping exit for a fraction of second will do the trick.
Solution 3
for .net 4.5 and greater versions and mongodriver 2x series follow the below code
var Client = new MongoClient();
var MongoDB = Client.GetDatabase("shop");
var Collec = MongoDB.GetCollection<BsonDocument>("computers");
var documnt = new BsonDocument
{
{"Brand","Dell"},
{"Price","400"},
{"Ram","8GB"},
{"HardDisk","1TB"},
{"Screen","16inch"}
};
Collec.InsertOneAsync(documnt);
Console.ReadLine();
Related videos on Youtube
Author by
Chandan
Updated on March 29, 2020Comments
-
Chandan about 4 years
- I'm using the
MongoClient
in my c# console application to connect to MongoDB
https://github.com/mongodb/mongo-csharp-driver/releases/tag/v2.0.0-rc0
-
My code
class Program { static void Main(string[] args) { const string connectionString = "mongodb://localhost:27017"; // Create a MongoClient object by using the connection string var client = new MongoClient(connectionString); //Use the MongoClient to access the server var database = client.GetDatabase("test"); var collection = database.GetCollection<Entity>("entities"); var entity = new Entity { Name = "Tom" }; collection.InsertOneAsync(entity); var id = entity._id; } } public class Entity { public ObjectId _id { get; set; } public string Name { get; set; } }
-
After successfully running the code above, I'm unable to find this record in the MongoDB database using this command:
db.entities.find().pretty()
What's wrong with my code?
- I'm using the
-
Richard II almost 9 yearsif you know why this code works, and why the other one failed, it would be helpful to include such info in your answer. Knowing why something works or not (even if the reason is "bug in the API") can help the reader improve far beyond helping him in just this one narrow example.
-
Naveed Ahmad over 8 yearsIn console application, I guess it was exiting the application before the store was created. I added the async method, followed by readline in main static method and it started working. static void Main(string[] args) { DoSomethingAsync(); Console.ReadLine(); }
-
Baahubali over 8 yearslookd like async method and await keyword at the collection.InsertOneAsyc did the trick as mentioned by @Inba in the post above
-
XtrmJosh over 7 yearsMongoDB is already a namespace, I assume this code won't compile?
-
Tom Stickel almost 7 yearsasync/await would wait and indeed if a timeout error the catch block would then get hit. I'm not sure that is the reason it is "working" because of adding async/await
-
RickWeb over 6 yearsYou are correct it is a Namespace but, you have probably defined it in the using statements, so this code would work fine. There would be no issue using this as a local variable name. Although personally I would avoid this, more for my own confusion than anything else.