簡體   English   中英

使用 C# 讀取 MongoDB 中的字段值

[英]Reading field's value in MongoDB with C#

我有 Mongo 數據庫。 我需要 output 字段的值在我的集合中,但我只能 output 文檔。 我需要 output doc.Name、doc.Email 和 doc.Password。 謝謝!

class Program
{
    static void Main(string[] args)
    {
        var dbClient = new MongoClient("mongodb://127.0.0.1:27017");
        IMongoDatabase db = dbClient.GetDatabase("Authentication");
        string[] testlit;
        var cars = db.GetCollection<BsonDocument>("Accounts");
        var documents = cars.Find(new BsonDocument()).ToList();
        foreach (BsonDocument doc in documents)
        {
            Console.WriteLine(doc.ToString());
        }
        Console.ReadLine();
    }
}

你可以這樣做

var dbClient = new MongoClient("mongodb://127.0.0.1:27017");
IMongoDatabase db = dbClient.GetDatabase("Authentication");
var accounts = db.GetCollection<BsonDocument>("Accounts");
//accounts.InsertOne(new BsonDocument(new Dictionary<string, object>
//{
//    ["Name"] = "Name of account", ["Email"] = "myemail@account.com",
//    ["Password"] = "don't ever do that to me. I hope this is a hash...",
//    ["SomeOtherField"] = "don't need it"
//}));
var projection = Builders<BsonDocument>.Projection.Include("Name").Include("Email").Include("Password").Exclude("_id");
var documents = accounts.Find(new BsonDocument()).Project(projection).ToList();
foreach (BsonDocument doc in documents)
{
    Console.WriteLine($"Name: {doc.GetValue("Name")}\nEmail: {doc.GetValue("Email")}\nPassword: {doc.GetValue("Password")}");
    //Name: Name of account
    //Email: myemail @account.com
    //Password: don't ever do that to me. I hope this is a hash...
}

通過投影,字段在數據庫中包含/排除。 更少的數據傳輸。 如果您稍后需要這些值,請忽略projection部分。 您可以使用doc.GetValue擁有您的字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM