MongoDB/C# 获取所有文档中某个键的所有值
我有一个名为“employees”的 MongoDB 集合,其中有这样的文档:
{
"_id": "4dc077b07701540f34000001",
"FullName": "Fullname...",
"FirstName": "First name...",
"LastName": "Last name...",
"Title": "Title... ",
"Location": "Location...",
"Customer": "Customer...",
"Phone": "Phone...",
"CellPhone" : "Cellphone...",
"EMail": "E-mail..."
}
我正在尝试创建一种方法,对集合中的所有文档执行 foreach 循环,并将 FullName-key 的每个值放入列表中。
List<string> listed = new List<string>();
IMongoCollection collection = _db.GetCollection("employees");
//var list = collection.FindAll().Documents.ToList();
var persons = from p in collection.AsQueryable()
select p["FullName"];
//foreach (var lt in list)
foreach (var name in persons)
{
//listed.Add(lt["FullName"].ToString());
listed.Add(name.ToString());
}
return listed;
上面是我尝试过的代码,带注释的代码返回 NullReferenceException,未注释的代码返回列表中的整个文档。
我的问题是:我必须执行什么样的查询才能将名为“FullName”的每个键的每个值放入列表中?我在 Windows 7 上使用当前的 MongoDB 稳定版本,并且使用 MongoDB-CSharp 社区驱动程序。感谢所有帮助和指示!
I have a MongoDB collection called "employees" where there are documents like this:
{
"_id": "4dc077b07701540f34000001",
"FullName": "Fullname...",
"FirstName": "First name...",
"LastName": "Last name...",
"Title": "Title... ",
"Location": "Location...",
"Customer": "Customer...",
"Phone": "Phone...",
"CellPhone" : "Cellphone...",
"EMail": "E-mail..."
}
I am trying to make a method that does a foreach loop on all documents in the collection and puts each value of the FullName-key and adds it to a List.
List<string> listed = new List<string>();
IMongoCollection collection = _db.GetCollection("employees");
//var list = collection.FindAll().Documents.ToList();
var persons = from p in collection.AsQueryable()
select p["FullName"];
//foreach (var lt in list)
foreach (var name in persons)
{
//listed.Add(lt["FullName"].ToString());
listed.Add(name.ToString());
}
return listed;
Above is the code I have tried, the commented-code returns a NullReferenceException, the uncommented code returns the whole document in a list.
My question is: What kind of query must I do to get each value for every key called "FullName" into a list? I am using the current MongoDB stable version on Windows 7, and I am using the MongoDB-CSharp community driver. All help and pointers are appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
应该做吗?
但是,您应该考虑使用通用方法,如下所示:
http:// /www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-GetCollection方法
Should do it?
However you should consider using the generic methods as seen in:
http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-GetCollectionmethod