Home > Software design >  Trying to get the name of each user in my MongoDB Database
Trying to get the name of each user in my MongoDB Database

Time:09-14

i have a MongoDB Database for my discord but i'm making a simple c# app that will access the database and show each users name and level this is my current code

using MongoDB.Bson;
using MongoDB.Driver;

namespace ExampleApp
{
    class Program
    {
        static async Task Main()
        {
            MongoClient dbClient = new MongoClient("Connection String");

            var database = dbClient.GetDatabase("test");
            var collection = database.GetCollection<BsonDocument>("users");
            var firstDocument = collection.Find(new BsonDocument()).ForEachAsync(user =>
            {
                Console.WriteLine(user);
            });
            Console.Read();
        }
    }
}

i can't figure out how to print each users name and level like user.name or user.level isn't a thing

CodePudding user response:

You can access the properties of the BsonDocument like this:

Console.WriteLine($"{user["name"].AsString} - {user["level"].AsInt32}");

The indexer is used to retrieve the value. Based on this, you can use the As*-properties to convert the value to the desired data type. Above sample assumes that name is a string and level is an Int32 (int).

  • Related