我是C#/。NET的新手,我一直在尝试在字典应用程序中实现数据库服务器(仅出于学习目的),您可以从列表框中选择单词,它将在文本框中显示值。 我正在尝试仅获取名为“单词”和“翻译”的键的列表
这是bson(json)文档
{
"_id": "5ca01f8e36601d012c7b2da1",
"Word": "Bonjour",
"Translation": "Hello",
"Word_Type": "Something",
"Synonyms": "Salut",
"Use_Cases": "Bonjour, comment vas-tu?",
"Definition": "It's a Greeting"
}
这是我用来从数据库获取数据的代码:
private MongoClient client = new MongoClient("mongodb://localhost:27017");
/// <summary>
/// All the data needed for words
/// </summary>
public class DWord
{
public ObjectId _id { get; set; }
public string Word { get; set; }
public string Translation { get; set; }
public string Word_Type { get; set; }
public string Synonyms { get; set; }
public string Use_Cases { get; set; }
public string Definition { get; set; }
}
private void MethodThatGetsData()
{
var database = client.GetDatabase("DictDB");
var collection = database.GetCollection<BsonDocument>("Words");
var records = collection.Find(new BsonDocument()).ToList();
// I tried using foreach, but I don't know how to get the keys in that bsondocument (called "record" below)
foreach (string record in records)
{
WordsListBox.Items.Add(record);
}
}
我想知道如何获取每条记录的键值,谢谢您的帮助
答案 0 :(得分:0)
将循环替换为以下内容:
foreach (BsonDocument record in records)
{
IEnumerable<string> names = record.Names;
// Do something with the names...
}
注意,对记录进行枚举会为每个查找结果返回一个BsonDocument。