C# : Retrieve array values from bson document

孤者浪人 提交于 2019-12-07 00:50:01

问题


In my MongoDB collection, I have a document with an array entry. How do I get these array values as a string array in C#? I can get the document itself back fine but I can't seem to get the array values. This is where I'm up to :

QueryDocument findUser = new QueryDocument("_id" , id);
BsonDocument user = bsonCollection.FindOne(findUser);

So in this user document, there is an array that I'd like to get and parse into a string array. The document looks something like this :

{
  "firstname" : "jon",
  "secondname" : "smith",
  "loves" : ["this","that","other stuff"]
}

回答1:


If I got your problem correctly, One approach is :

var queryString = Query.EQ("_id", id);
var resultBsons = collection.FindOne(queryString);
var arrayOfStrings = resultBsons["loves"].AsBsonArray.Select(p => p.AsString).ToArray();


来源:https://stackoverflow.com/questions/27047165/c-sharp-retrieve-array-values-from-bson-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!