I have Mongo DataBase. I need to output field's values in my collection, but I can output only document. I need to output doc.Name, doc.Email and 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. You can have your fields with doc.GetValue
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.