Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Can't access Count property from BsonArray with C# driver

I just want to prephase this by saying that this could just be a PEBCAK but I’m not sure so that’s why I’m posting here. I’m trying to convert the results of a GraphLookup to a full hierarchy in C#. To check if an array is empty I’m trying to run this:

    var MatchStage = new BsonDocument("$match", new BsonDocument{
    	{"Parent", BsonNull.Value},
    });
    var GraphLookupStage = new BsonDocument("$graphLookup", new BsonDocument{
    	{"from", "entries"},
    	{ "startWith", "$_id" },
    	{ "connectFromField", "_id"},
    	{ "connectToField",  "Parent.ID" },
    	{ "as", "children" },
    	{ "depthField", "route" }
    });
    var document = collection.Aggregate<BsonDocument>(new BsonDocument[] {
    	MatchStage,
    	GraphLookupStage
    }).ToList();
    foreach (var val in document)
    {
    	if (val["children"].Count == 0)
    	{
    		Console.WriteLine("True");
    	} else {
    		Console.WriteLine("False");
    	}
    };

Here is the data I’m getting out:

[
	{
		"_id" : UUID("234350d9-775c-4fa2-9a1e-54bd7861d511"),
		"test" : "parent",
		"children" : [
			{
				"_id" : UUID("75b1b366-697c-4690-b216-ca91151f61a6"),
				"Parent" : {
					"ID" : UUID("234350d9-775c-4fa2-9a1e-54bd7861d511"),
					"Slot" : 1
				},
				"test" : "child2",
				"route" : NumberLong(0)
			},
			{
				"_id" : UUID("ba567231-443f-412b-af57-ae8a134c57e1"),
				"Parent" : {
					"ID" : UUID("234350d9-775c-4fa2-9a1e-54bd7861d511"),
					"Slot" : 1
				},
				"test" : "child3",
				"route" : NumberLong(0)
			},
			{
				"_id" : UUID("4f80a73e-31eb-44bb-8426-68ee58b6b0fc"),
				"Parent" : {
					"ID" : UUID("234350d9-775c-4fa2-9a1e-54bd7861d511"),
					"Slot" : 1
				},
				"test" : "child1",
				"route" : NumberLong(0)
			},
			{
				"_id" : UUID("7bd5efe0-707a-4c4d-9265-8d65d9c406b4"),
				"Parent" : {
					"ID" : UUID("75b1b366-697c-4690-b216-ca91151f61a6"),
					"Slot" : 1
				},
				"test" : "test2",
				"route" : NumberLong(1)
			}
		]
	},
	{
	"_id" : UUID("f1745729-7862-42a1-8545-cf6a243c9bd2"),
	"test" : "test2",
	"children" : [

	]
	}
]

From what I can see I should be getting 1 “True” and 1 “False” in console. Instead I get an error. Where have I screwed up?

Hi @Lukas_Friman,

This is because val["children"] is an instance type of BsonValue and not BsonArray. You could convert BsonValue to BsonArray using AsBsonArray property.

For example:

val["children"].AsBsonArray.Count

Regards,
Wan.