简体   繁体   中英

C# : Retrieve array values from bson document

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"]
}

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

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.

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