简体   繁体   English

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

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

I have Mongo DataBase.我有 Mongo 数据库。 I need to output field's values in my collection, but I can output only document.我需要 output 字段的值在我的集合中,但我只能 output 文档。 I need to output doc.Name, doc.Email and doc.Password.我需要 output doc.Name、doc.Email 和 doc.Password。 Thank you!谢谢!

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();
    }
}

You may do it like你可以这样做

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...
}

With projection the fields are included/excluded at database.通过投影,字段在数据库中包含/排除。 Less data travels.更少的数据传输。 If you need the values later, leave out the projection part.如果您稍后需要这些值,请忽略projection部分。 You can have your fields with doc.GetValue .您可以使用doc.GetValue拥有您的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM