I am using Official Mongodb C# driver. It allows us to build a nested document structure. Now, Querying on these documents is tedious task to do since it requires a fully qualified dot notation to reference exactly the document in question. For this I want to retrieve all parent document keys, so that I can select one of them and appends to the string and pass to the .Query . I am able to get all the outer keys recursively but I don’t know how to get the names of the outer keys one level less than the entered key.
The Code which I am using to get all keys is as follows:
void Print(BsonDocument document)
{
foreach (var element in document)
{
bool a = element.Value.IsBsonDocument;
if (element.Value.IsBsonDocument)
{
Console.WriteLine(element.Name);
Print(element.Value.AsBsonDocument);
Console.WriteLine("\n");
}
}
The document is the main document which I get by FindOneById(Id) method
To make sure I understand, your question is how to find out the key names of the subobjects one level down?
In the inner if-statement, calling element.Value.AsBsonDocument should return you a BSON document. You should then be able to iterate over the fields in that document in the same way that you iterated over the fields of the outer document. Your resulting code would probably look something like: