To write data to a MongoDB database using .NET, you can use the MongoDB .NET Driver. Here’s an example code
using System; using MongoDB.Bson; using MongoDB.Driver; class Program { static void Main() { // Connection string for the MongoDB database string connString = "mongodb://localhost:27017"; // Create a new MongoClient MongoClient client = new MongoClient(connString); // Access the database IMongoDatabase database = client.GetDatabase("your_database"); // Access the collection IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("your_collection"); // Create a new document var document = new BsonDocument { { "name", "John Doe" }, { "age", 30 }, { "email", "[email protected]" } }; // Insert the document into the collection collection.InsertOne(document); Console.WriteLine("Document inserted successfully!"); } }
In this example, replace 'mongodb://localhost:27017'
with the actual connection string for your MongoDB database.
The code creates a new MongoClient
instance using the connection string. It then accesses the desired database using GetDatabase
and the collection within that database using GetCollection
.
A new BsonDocument
is created to represent the data you want to insert. It contains fields such as "name"
, "age"
, and "email"
with their respective values.
The InsertOne
method is used to insert the document into the collection.
Finally, a success message is displayed in the console.
Make sure to have the MongoDB .NET Driver installed in your .NET project. You can install it via NuGet Package Manager or through the .NET CLI:
dotnet add package MongoDB.Driver
Remember to handle any exceptions that may occur during the connection or document insertion for proper error handling.