To read data from a MongoDB database using .NET, you can use the MongoDB .NET Driver. Here’s an example code:
using System; 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 filter to retrieve documents var filter = Builders<BsonDocument>.Filter.Empty; // Retrieve documents from the collection var documents = collection.Find(filter).ToList(); // Iterate over the documents and print the values foreach (var document in documents) { string name = document["name"].AsString; int age = document["age"].AsInt32; string email = document["email"].AsString; Console.WriteLine($"Name: {name}, Age: {age}, Email: {email}"); } } }
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 filter is created to retrieve all documents in the collection. The Find
method is used to execute the query and retrieve the documents as a list.
The code then iterates over the retrieved documents and accesses the desired fields by their names using the AsString
or AsInt32
methods.
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 query execution for proper error handling.