Home > Back-end >  C# MongoDB - Get all elements inside a BsonArray
C# MongoDB - Get all elements inside a BsonArray

Time:10-27

I have a collection with a document containing a BsonArray. Like this

{
  "_id": {
    "$oid": ""
  },
  "Types": [
    "Type 1",
    "Type 2",
    "Type 3"
  ]
}

I want to get all the "Type" values inside "Types" so I can create a List of strings in C#, I can get the document containing the Types array but I can't create the List because the result I get is of type BsonElement.

This is my code so far

var filter = Builders<BsonDocument>.Filter.Exists("Types", true);
var projection = Builders<BsonDocument>.Projection.Include("Types").Exclude("_id");
var result = collection.Find(filter).Project(projection).First();

The projection seems to be working because the result I get is this but I can't get the elements in a list.

Types=["Type 1", "Type 2", "Type 3"]

CodePudding user response:

If I do not misunderstand your question, you are trying to convert from BsonArray to List<string>.

Working with System.Linq to convert each BsonValue to string type and output the result with List<string> type.

using MongoDB.Bson;
using System.Collections.Generic;
using System.Linq;

List<string> types = ((BsonArray)result["Types"]).Values
    .Select(x => x.AsString)
    .ToList();

enter image description here

  • Related