You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#程序中获取MongoDB中Discord用户的名称与等级?

问题根源

你用的BsonDocument是弱类型的文档对象,它没有直接暴露name或level这类属性,所以无法通过.运算符直接访问字段值。以下是两种可行的解决方法:


方法1:直接使用BsonDocument索引器访问字段

通过[]索引器获取对应字段的值,再根据字段实际类型做转换:

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");
            // 必须await异步方法,否则可能未完成遍历就进入等待输入
            await collection.Find(new BsonDocument()).ForEachAsync(user =>
            {
                // 按MongoDB中的实际字段名索引取值,按需转换类型
                string userName = user["name"].ToString();
                int userLevel = user["level"].AsInt32();
                Console.WriteLine($"用户名:{userName},等级:{userLevel}");
            });
            Console.Read();
        }
    }
}

如果字段可能不存在,建议用TryGetValue避免报错:

await collection.Find(new BsonDocument()).ForEachAsync(user =>
{
    if (user.TryGetValue("name", out BsonValue nameVal) && user.TryGetValue("level", out BsonValue levelVal))
    {
        string userName = nameVal.ToString();
        int userLevel = levelVal.AsInt32();
        Console.WriteLine($"用户名:{userName},等级:{userLevel}");
    }
    else
    {
        Console.WriteLine("当前文档缺少名称或等级字段");
    }
});

方法2:使用强类型实体类(推荐)

创建与MongoDB用户文档结构对应的实体类,实现强类型访问,代码更清晰易维护:

  1. 定义User实体类:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class User
{
    // 对应MongoDB中的_id字段
    [BsonId]
    public ObjectId Id { get; set; }

    // 属性名与MongoDB字段名一致,或用BsonElement指定映射关系
    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("level")]
    public int Level { get; set; }
}
  1. 修改主程序代码使用强类型集合:
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<User>("users");
            await collection.Find(new BsonDocument()).ForEachAsync(user =>
            {
                // 直接访问实体类属性
                Console.WriteLine($"用户名:{user.Name},等级:{user.Level}");
            });
            Console.Read();
        }
    }
}

内容的提问来源于stack exchange,提问作者FearlessNite345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:20:29